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.
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:and execute it as the child proces which will show some CPU usage.