-2

Possible Duplicate:
Working of fork() in linux gcc
Why does this code print two times?

#include<stdio.h>
main()
{

 printf("hello\n");
 fork();

}

The above code prints "hello" one time.The code below prints "hello" two times.

#include<stdio.h>
main()
{

 printf("hello");
 fork();

}

The code above prints "hello" two times.

Please Somebody explain this strange behavior.

Community
  • 1
  • 1
Suraj Menon
  • 1,486
  • 3
  • 28
  • 50

1 Answers1

3

It's not guaranteed to behave in this way, but the usual behaviour is: With

printf("hello");

the "hello" is printed to the output buffer, but that buffer is not yet flushed. Then upon the

fork();

the program state is copied to the child process, including the non-empty output buffer. Upon exit, the output buffers of parent and child are both flushed.

With the newline, the output buffer is flushed before the fork().

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431