Why does a program with fork() sometimes print its output multiple times?
When outputting to standard output using the C library's printf()
function, the output is usually buffered. The buffer is not flushed until you output a newline, call fflush(stdout)
or exit the program (not through calling _exit()
though). The standard output stream is by default line-buffered in this way when it's connected to a TTY.
When you fork the process in "Program 2", the child processes inherits every part of the parent process, including the unflushed output buffer. This effectively copies the unflushed buffer to each child process.
When the process terminates, the buffers are flushed. You start a grand total of eight processes (including the original process), and the unflushed buffer will be flushed at the termination of each individual process.
It's eight because at each fork()
you get twice the number of processes you had before the fork()
(since they are unconditional), and you have three of these (23 = 8).
It does not affect the fork in any way.
In the first case, you end up with 8 processes with nothing to write, because the output buffer was emptied already (due to the \n
).
In the second case you still have 8 processes, each one with a buffer containing "Hello world..." and the buffer is written at process end.
@Kusalananda explained why the output is repeated. If you are curious why the output is repeated 8 times and not only 4 times (the base program + 3 forks):
int main()
{
printf("hello world...");
fork(); // here it creates a copy of itself --> 2 instances
fork(); // each of the 2 instances creates another copy of itself --> 4 instances
fork(); // each of the 4 instances creates another copy of itself --> 8 instances
}