0

我阅读了关于APUE 3rd 8.16 Process Scheduling 的信息,有一个示例用于验证更改进程的 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
parent nice:20
child nice:20,adjusted by 0
child now nice:20
parent count:601089419
child count:603271014
看起来对子进程没有任何影响,为什么?以及如何使结果符合我的预期?
(我的平台是:Linux liucong-dell 4.4.0-93-generic #116~14.04.1-Ubuntu SMP Mon Aug 14 16:07:05 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux)

4

1 回答 1

1

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

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

于 2017-09-07T13:21:50.540 回答