In the code below, do the forks actually run in parallel or one after another?
What is the meaning of wait(NULL)
?
(The program creates an n number of child processes, n is supplied via command line)
int main ( int argc, char *argv[] ) {
int i, pid;
for(i = 0; i < atoi(argv[1]); i++) {
pid = fork();
if(pid < 0) {
printf("Error occured");
exit(1);
} else if (pid == 0) {
printf("Child (%d): %d\n", i + 1, getpid());
exit(0);
} else {
wait(NULL);
}
}
}
They do run in parallel, up until the point that one of them waits.
wait(NULL)
or more accuratelywait(0)
means wait until a state change in the child process. To find out about Unix / Linux C api calls, typeman <function Name>
on the command line. You'll need to get used to reading those pages, so better start now.In your case
would have given you what you needed.
Since you've only
fork(...)
ed once, you have only one child. The parent waits until it changes state, and since the child's state during the fork is the same as the parent's state prior to the fork (that of running), the likely outcome is that the parent waits until the child dies. Then the parent will continue executing, but since it doesn't have much to do after thewait(...)
call, it will quickly exit too.