Understand the workflow, beware of fork bombing your system.
- While you rarely have reason to use fork this way (and you shouldn't, or you'll begin to tax the shared system you're working on and/or hit your limit on the number of concurrent processes), it's instructive to trace through a short program where forked processes themselves call fork.
- Code is in lecture examples folder: processes/fork-puzzle.c. Code is also right here.
- Check this out:
static const char const *kTrail = "abcd";
static const int kForkFail = 1;
int main(int argc, char *argv[]) {
size_t trailLength = strlen(kTrail);
for (size_t i = 0; i < trailLength; i++) {
printf("%c\n", kTrail[i]);
pid_t pid = fork();
exitIf(pid == -1, kForkFail, stderr, "Call to fork failed.");
}
return 0;
}
- Reasonably obvious: One a is printed by the soon-to-be-great-grandaddy process.
- Less obvious: The first child and the parent each return from fork and continue running in mirror processes, each with their own copy of the global "abcd" string, and each advancing to the i++ line within a loop that promotes a 0 to 1. It's hopefully clear now that two b's will be printed.
- Key questions to answer:
- How many c's get printed?
- How many d's get printed?
- Are both b's necessarily printed one after another?