We can do the same thing, but reap in the order they are forked.
- Look at this lovely program of octuplets (code is in lecture examples folder processes/reap-in-fork-order.c and can also be viewed right here)
int main(int argc, char *argv[]) {
pid_t children[kNumChildren];
for (size_t i = 0; i < kNumChildren; i++) {
children[i] = fork();
exitIf(children[i] == -1, kForkFail, stderr, "Fork function failed.\n");
if (children[i] == 0) exit(110 + i);
}
for (size_t i = 0; i < kNumChildren; i++) {
int status;
exitUnless(waitpid(children[i], &status, 0) == children[i],
kWaitFail, stderr, "Intentional wait on child %d failed.\n", children[i]);
exitUnless(WIFEXITED(status) && WEXITSTATUS(status) == 110 + i,
kExitFail, stderr, "Correct child %d exited abnormally.\n");
}
return 0;
}
- This version spawns and reaps child processes in some first-spawned-first-reaped (let's invent an acronym: FSFR) manner.
- Understand, of course, that the child processes aren't required to exit or otherwise terminate in FSFR order. In theory, the first child thread could finish last, and the reap loop could be held up on its very first iteration until the first child actually finishes. But the process zombies (as they're called) are certainly reaped in the order they were forked.