To elaborate on the answer in the linked question and relate it to your question, stdout
generally buffers input until it sees a \n
, or you explicitly fflush
it.
When you have the \n
there, you are making it flush before the fork()
.
Without the \n
, it flushes after the fork, so it will exist in both processes.
In the linked question, they talk about fflush()
, but \n
has the same effect of causing stdout
to flush.
You will see only one print with the program below as well:
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
int main()
{
printf("Hello world");
fflush(stdout);
fork();
}
Edit: Due to a comment from Dabo, \n
will only cause a flush if stdout
is in line buffering mode instead of full buffering mode. We can observe in the following program that we still see the string printed twice, even with \n
, when full buffering mode is turned on using setvbuf
.
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
int main()
{
setvbuf(stdout, NULL,_IOFBF, BUFSIZ);
printf("Hello world\n");
fork();
}
Output:
Hello world
Hello world