Reaping multiple child processes:
- Of course, the parent is allowed to call fork multiple times, provided it eventually reaps the child processes after they exit.
- If we want to reap child processes as they exit without concern for the ordering in which they fork, then this does the trick:
- Check this out (code is in lecture examples folder processes/reap-as-they-exit.c and can also be viewed right here)
int main(int argc, char *argv[]) {
for (size_t i = 0; i < kNumChildren; i++) {
pid_t pid = fork();
exitIf(pid == -1, kForkFail, stderr, "Fork function failed.\n");
if (pid == 0) exit(110 + i);
}
while (true) {
int status;
pid_t pid = waitpid(-1, &status, 0);
if (pid == -1) break;
if (WIFEXITED(status)) {
printf("Child %d exited: status %d\n", pid, WEXITSTATUS(status));
} else {
printf("Child %d exited abnormally.\n", pid);
}
}
exitUnless(errno == ECHILD, kWaitFail, stderr, "waitpid failed.\n");
return 0;
}
- Note we feed a -1 as the first argument to waitpid. That -1 states we want to hear about any child as it exits.
- Eventually, all children exit (normally or not) and waitpid correctly returns -1 to signal that all child processes have ended.
When waitpid returns -1, it sets a global variable called errno to the constant ECHILD as a signal that -1 was returned because all child processes terminated. Interestingly enough, that's the "error" we want.