我有这个编程任务,我需要使用getrusage来找到'孩子们在做什么',正如我的教授说的那样。我在RUSAGE_CHILDREN
的“默认”部分中使用了getrusage函数的switch(fork())
模式。我只需要占用内核和用户时间。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, const char * argv[]) {
char **cmd;
int i = 1;
pid_t child_pid;
struct rusage child_ru;
if (argc == 1){
perror("No command inserted!\n");
exit(EXIT_FAILURE);
} else if(argc == 50){
perror("No command inserted!\n");
exit(EXIT_FAILURE);
}
cmd = (char **) malloc( (argc) * sizeof(char *));
cmd[0] = (char *) malloc( strlen(argv[1] + 1 ) * sizeof(char) );
strcpy(cmd[0], argv[1]);
if (argc > 2){
for (i = 1 ; i < argc - 1 ; i++ ){
cmd[i] = (char *) malloc( strlen(argv[i+1] + 1 ) * sizeof(char) );
strcpy(cmd[i], argv[i+1]);
}
}
cmd[i] = NULL;
switch (child_pid = fork()) {
case -1:
perror("Error in fork()!\n");
break;
case 0:
execvp(cmd[0], cmd);
perror("Failed Execution or not existing command!!\n");
exit(EXIT_FAILURE);
default:
printf("Command PID: %ld", (long)child_pid);
if(wait(NULL) ==-1)
perror("Error in wait()\n");
if (getrusage(RUSAGE_CHILDREN, &child_ru) == -1)
perror("Error in getrusage()\n");
printf("\n");
printf("CPU time: %lld.%lld sec\n", (long long)child_ru.ru_utime.tv_sec,(long long)child_ru.ru_utime.tv_usec);
printf("Kernel time: %lld.%lld sec\n", (long long)child_ru.ru_stime.tv_sec, (long long)child_ru.ru_stime.tv_usec);
break;
}
return 0;
}
这是我的计划。我总是让内核的时间小于用户的时间,即使对于I / O命令,所以我认为某处有错误,但我不知道它在哪里,是我第一次使用getrusage。