首页 文章

改变流程的良好 Value 对Linux没有影响

提问于
浏览
0

我读了一下APUE 3rd,8.16进程调度,有一个编写的例子来验证改变进程的nice值会影响它的优先级,我重写代码如下:

#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>

long long count;
struct timeval end;
static void check_time(const char* str);

int main(int argc, char* argv[])
{
    pid_t pid;
    char* s;
    int nzero, ret;
    int adj = 0;
    setbuf(stdout, NULL);
#if defined(NZERO)
    nzero = NZERO;
#elif defined(_SC_NZERO)
    nzero = sysconf(_SC_NZERO);
#else
#error NZERO undefined
#endif
    printf("NZERO = %d\n", nzero);
    if (argc == 2)
        adj = strtol(argv[1], NULL, 10);
    gettimeofday(&end, NULL);
    end.tv_sec += 10;
    if ((pid = fork()) < 0) {
        perror("fork error");
        return -1;
    } else if (pid == 0) {
        s = "child";
        printf("child nice:%d, adjusted by %d\n", nice(0) + nzero, adj);
        errno = 0;
        if ((ret = nice(adj)) == -1 && errno != 0) {
            perror("nice error");
            return -1;
        }
        printf("child now nice:%d\n", ret + nzero);
    } else {
        s = "parent";
        printf("parent nice:%d\n", nice(0) + nzero);
    }
    while (1) {
        if (++count == 0) {
            printf("count overflow\n");
            return -1;
        }
        check_time(s);
    }
    return 0;
}

static void check_time(const char* str)
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    if (tv.tv_sec >= end.tv_sec && tv.tv_usec >= end.tv_usec) {
        printf("%s count:%lld\n", str, count);
        exit(0);
    }
}

示例的结果如下所示:
NZERO = 20
父母好:20
孩子好看:20,调整为0
孩子现在很好:20
父母数:601089419
子女数:603271014
看起来没有对子进程产生任何影响,为什么?以及如何以我期望的方式取得成果?
(我的平台是:Linux liucong-dell 4.4.0-93-generic#116~14.04.1-Ubuntu SMP Mon 8月14日16:07:05 UTC 2017 x86_64 x86_64 x86_64 GNU / Linux)

1 回答

  • 1

    您的多核CPU可以同时愉快地运行父级和子级 . 只要两者都可以运行,它们的相对优先级无关紧要 .

    为了查看 nice 的效果,您必须加载机器,以便始终准备好进程并等待运行 . 最简单的方法是让您的测试成为多线程 . Spawn(在 fork 之后)在parend和child中的一些工作线程,使它们都递增计数器(使其成为原子或线程本地),并看看会发生什么 .

相关问题