C - using getrusage for children user and kernel time

339 views Asked by At

I have this programming assignment in which I need to use the getrusage to find 'what the children is doing', as my professor said. I used the RUSAGE_CHILDREN mode of the getrusage function inside the 'default' section of the switch(fork()). I simply need to take the kernel and user time.

#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;
}

This is my program. I always get the time of the kernel smaller than the time of the user, even for I/O command, so I think there's an error somewhere, but I don't know where it is, is my first time using getrusage.

0

There are 0 answers