When you use stdio
, stdout
is fully-buffered unless it's writing to a terminal; when writing to a terminal it's line-buffered.
So if you run Program 1 with output redirected to a file or pipe, printf
writes the line to the output buffer, but doesn't flush the buffer. When the process forks, the buffer is duplicated in both processes. When they exit, they each flush their copy of the buffer, which prints the line.
You would get the same result in Program 2 if you'd written:
cout << "Hi , " <<getpid() << "\n";
But endl
, in addition to outputting the newline character, also flushes the buffer. The equivalent in Program 1 would be:
printf("Hi , %d\n" , getpid());
fflush(stdout);