can anyone explain why the output of
main()
{
printf("hello ");
fork();
printf("hello ");
}
is:
hello hello hello hello
and the output of:
main()
{
printf("hello\n");
fork();
printf("hello ");
}
is:
hello
hello hello
what difference does \n make w.r.t to buffer?
When you
forkthe memory of the process is copied. This includesstdiobuffers, so if thehellostays in the buffer it will be printed by both processes. Both processes go on about their business and eventually flush their buffers and you see “hello” twice.Now on most implementations stdout is line-buffered which means a
\ntriggers a flush. So when theforkhappens the buffer is empty. A sure fire way to prevent this would be to flush everything before forking.EDIT
There are now two processes (parent & child) executing the same code so that
printfis executed twice.