I'm trying to find the run time of the fork()
system call. Each child process needs to immediately exit, and the parent needs to wait()
on each child before creating the next. I also want to use the shell built-in command named time
to measure the execution time of a program.
I have this code so far, but not sure If I'm doing it right.
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int global = 100;
int main(int argc, char** argv)
{
int local = 5;
pid_t pid;
pid = fork();
if (pid < 0) {
fprintf(stderr, "error -- failed to fork()");
return 1;
}
if (pid > 0) {
int child_ret;
waitpid(pid, &child_ret, 0);
printf("parent -- global: %i, local: %i\n", global, local);
printf("parent -- child exited with code %i\n", child_ret);
} else {
global++;
local++;
printf("child -- global: %i, local: %i\n", global, local);
exit (0);
}
}
getrusage
system call. – Intercontinentallocal
andglobal
don't change for your parent-process, but yes, your code looks correct. – Mezereonexit
in the child. You should call_exit
. If you callexit
in the child, it will run all the parent's "at exit" handlers, and the results of running an at exit handler twice can be unpredictable. This has caused serious bugs with security consequences in the past, so don't get into the habit of mismanaging processes. – Essene