4

Language: C, OS: Linux

Code:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main(void)
{
    fork();
    printf("hello world\n");
    fork();
    printf("bye\n");
    return 0;
}

Output:

hello world
bye
hello world
bye
hello world
bye
hello world
bye

According to this and this, printf() buffers output until a newline is encountered.

So why does we have 4 "hello world" in this case? (instead of 2 "hello world")

Edit: Sorry all, but like @GregHewgill said, I running this program from an environment where the output cannot be directly to the terminal, when I check it again on my computer, it just run as expected.

Community
  • 1
  • 1
lzutao
  • 409
  • 5
  • 13

1 Answers1

2

According to this and this, printf() buffers output until a newline is encountered.

Printing a newline usually flushes only if the output goes to a terminal device. For example:

$ ./a.out >out_file

will not flush the buffer even with the newline character. So, your expectation is flawed.

The only right way to get "desired" output (2 hello world and 4 bye) is to either disable buffering totally using setbuf:

setbuf(stdout, 0);

or use fflush:

fflush(stdout);

after each printf call to flush explicitly.

P.P
  • 117,907
  • 20
  • 175
  • 238
  • It should be sufficient to ensure that the stream is line-buffered, which can be done via `setvbuf()`. It should not be necessary to disable buffering altogether, though perhaps that would be safer. – John Bollinger Mar 27 '17 at 17:40