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