Part 3 of 6 · 2 min read
Counting forks
In plain words: A common exercise is to count processes. Each fork call is run by every process that reaches it, and each of them makes one child. So the number of processes doubles with each unconditional fork.
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
for (int i = 0; i < 3; i++) fork();
printf("hi\n");
while (wait(NULL) > 0);
return 0;
}
Trace by rounds: one process at the start. After the first fork, 2. After the second, 4. After the third, 8. Every one of the 8 prints hi, and running ./f4 | wc -l on the test machine counted 8 lines. The rule is 2 to the power of the number of forks: 2³ = 8.
A related trap is the output when the program prints text without a newline before forking. The program below prints A, forks, prints B, forks, and prints C with a newline:
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
printf("A");
fork();
printf("B");
fork();
printf("C\n");
while (wait(NULL) > 0);
return 0;
}
With output piped into a file, the result was four lines, each reading ABC. A reader might expect A once, B twice and C four times. The reason is buffering (Level 0, page 2). When output goes to a file or a pipe, the C library keeps text in a buffer and writes it later. The A was still in the buffer at the first fork, so the child inherited a buffer containing A. The same happened with B at the second fork. Each of the four processes then had ABC in its buffer and wrote it at exit. On a terminal the library writes at each newline, so the output differs. The safe habit is to call fflush(stdout) before fork, as the first program did.
Common mistake
Printing without a newline or flush just before fork causes the text to appear once per process. Flush before forking.
Check yourself:
1. How many processes exist after 4 unconditional forks, counting the original?
2. If a fork sits inside if (pid == 0), does the count still double?
3. Why does buffered output get duplicated?