I have the following code:
#include <stdio.h>
int main() {
printf("Hello\n");
fork();
return 0;
}
This gives output:
Hello
Which is as expected. But if i modify the code to:
#include <stdio.h>
int main() {
printf("Hello");
fork();
return 0;
}
Removing, the \n gives output:
HelloHello
Why is printf called two times. Isn't the child process supposed to execute the next instruction: return 0;
The printf
function call places the hello
characters into a buffer associated with the stdout
stream. The buffer is subsequently flushed when the process exits, and that's when we see the output. You've forked before this happened, so two processes perform this buffer flushing in two separate address spaces when each of them exits. Each process has a copy of the stream, with the buffer and its hello
contents.
When the stdout
stream is connected to an interactive device (like a TTY on Unix), then it is line buffered. Line buffering means that the buffer is flushed whenever a newline character is output.
If we flush the buffer before fork
(such as by printing a newline or by calling fflush(stdout)
) then the flushing takes place in the parent process. The buffer is empty at the time the fork
; though the child process inherits a copy of it, there is nothing left to flush in either process.
In the duplicated output case, something is in fact called twice. It's just not printf
, but rather the write
system call which sends the buffered characters to the output device.