2

我正在开发一个 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()工作原理。否则我看不到错误在哪里。

4

1 回答 1

1

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

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

struct timeval结构表示经过的时间。它在中声明sys/time.h并具有以下成员:

time_t tv_sec- 这表示经过时间的整秒数。

long int tv_usec- 这是剩余的经过时间(几分之一秒),以微秒数表示。它总是少于一百万。

于 2017-09-07T22:48:21.490 回答