2

正如我的教授所说,我有这个编程任务,我需要使用 getrusage 来查找“孩子们在做什么”。我RUSAGE_CHILDRENswitch(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。

4

0 回答 0