getrusage 子进程

getrusage on child process

我正在开发一个 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() 的工作原理。不然看不出哪里出错了

您只打印出 timeval 的 tv_sec,其中包含整数秒数。由于该程序不执行任何计算密集型操作,因此它的 CPU 时间(用户和系统)远小于 1 秒 - 大约 0.00001,因此您只会在微秒内获得非零值(tv_usec) 字段。

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

The struct timeval structure represents an elapsed time. It is declared in sys/time.h and has the following members:

time_t tv_sec - This represents the number of whole seconds of elapsed time.

long int tv_usec - This is the rest of the elapsed time (a fraction of a second), represented as the number of microseconds. It is always less than one million.