Rusage with wait4() does not show CPU time of finished child process

568 views Asked by At

I have a simple function which creates a child process, waits for it to finish and prints CPU system and user time.

int PrintChildProcessTime(char **arg)
{
    pid_t pid;
    int status;
    struct rusage usage;

    if ((pid=fork()) == 0)
    {
        execvp(arg[0],arg);

        perror("Execvp error");
        _exit(1);
    }
    else if (pid > 0)
    {
        wait4(pid, &status, 0, &usage);
        printf ("CPU time: %ld.%06ld sec user, %ld.%06ld sec system\n", usage.ru_utime.tv_sec, usage.ru_utime.tv_usec, usage.ru_stime.tv_sec, usage.ru_stime.tv_usec);
    }
    else
    {
        perror("Fork error");
        _exit(2);
    }
}

The thing is, even when I pass sleep 10 as **arg and the parent process waits for the child to finish, then it still shows 0.000000 in both system and user CPU time.

What am I doing wrong? Thank you for your help.

1

There are 1 answers

0
P.P On BEST ANSWER

That's because there's time spent by the child process either in user space or in the kernel space. sleep simply suspends the calling process and doesn't result in any CPU usage at all.

Instead make your child process do something and you'll see the CPU time.

For example, have a script called myscript with:

 #!/bin/bash

for((i=0;i<1000000;i++)); do
   echo hi >/dev/null
done

and execute it as the child proces which will show some CPU usage.