This question already has answers here:
Closed 2 years ago.
There are 2 different programs, they are small for example:
int main()
{
printf ("print hello");
fork();
}
int main()
{
printf ("print hello\n");
fork();
}
output 1 is: `print helloprint hello
output 2 is:print hello
The question is, why does the one with the \n
only print once, and the first one prints it twice?
You're running into the buffering behaviour of your system's printf
implementation. In the first case, the string is printed to a buffer, but since there's no newline (and you didn't call fflush
), it's just sitting there in that buffer. Then you fork, and both forked buffers are flushed when their respective processes exit.
In the second case, the \n
causes the buffer to be flushed before the fork, so there's no output remaining when the forked processes exit.
Change:
printf ("print hello");
fork();
to
printf ("print hello");
fflush(stdout);
fork();
By default, stdout
is usually line-buffered. In your example 2) you have the guarantee that stdout
is flushed before the fork
but in the example 1) it may happen after the fork
. Flushing stdout
before the fork
guarantee you to have the string printed before the fork
.