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?
Change:
to
By default,
stdout
is usually line-buffered. In your example 2) you have the guarantee thatstdout
is flushed before thefork
but in the example 1) it may happen after thefork
. Flushingstdout
before thefork
guarantee you to have the string printed before thefork
.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 callfflush
), 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.