儿童过程的怪诞

时间:2017-09-07 22:11:43

标签: c fork getrusage

我正在开发一个C程序,我必须fork()一个进程并使用getrusage()函数来打印用户时间和子进程的内核时间。

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/resource.h>
#include <sys/time.h>

int main(int argc, const char * argv[]) {

    struct rusage child1_usage, child2_usage;
    struct timeval child1_stime, child2_stime, child1_utime, child2_utime;
    pid_t child1_pid, child2_pid;



    switch (child1_pid = fork()) {

        case -1:
            perror("Fork failed!\n");
            break;

        case 0:

            printf("Hi I am the first child!!\nGive me one number and I multiply it by 4:\n");
            int num1;
            scanf("%d", &num1);
            printf("%d\n", num1*4);

            switch (child2_pid = fork()) {

                case -1:
                    perror("Second Fork failed!\n");
                    break;

                case 0:
                    printf("Hi I am the grand child!!\nGive me one number and I multiply it by 3:\n");
                    int num2;
                    scanf("%d", &num2);
                    printf("%d\n", num2*4);
                    getrusage(RUSAGE_SELF, &child2_usage);
                    child2_utime = child2_usage.ru_utime;
                    child2_stime = child2_usage.ru_stime;
                    printf("Time in user mode: %lld\n", (long long) child2_utime.tv_sec);
                    printf("Time in kernel mode: %lld\n", (long long) child2_stime.tv_sec);

                default:
                    sleep(10);
                    break;

            }

            getrusage(RUSAGE_SELF, &child1_usage);
            child1_utime = child1_usage.ru_utime;
            child1_stime = child1_usage.ru_stime;
            printf("Time in user mode: %lld\n", (long long) child1_utime.tv_sec);
            printf("Time in kernel mode: %lld\n", (long long) child1_stime.tv_sec);

        default:
            sleep(10);
            break;
    }

    return 0;
}

我的输出都是零...可能我误解了getrusage()是如何工作的。否则我看不出错误在哪里。

1 个答案:

答案 0 :(得分:0)

您只打印出timeval&#39; tv_sec,其中包含整秒数。由于程序不做任何计算密集型操作,因此其CPU时间(用户和系统)远小于1秒 - 大约0.00001,因此您只能在微秒内获得非零值({{ 1}})field。

https://www.gnu.org/software/libc/manual/html_node/Elapsed-Time.html

  

tv_usec结构代表经过的时间。它在struct timeval中声明,并具有以下成员:

     

sys/time.h - 这表示经过时间的整秒数。

     

time_t tv_sec - 这是剩余的经过时间(几分之一秒),表示为微秒数。它总是不到一百万。