Why output is different between to shell and to a file Why output is different between to shell and to a file bash bash

Why output is different between to shell and to a file


Because when you output to shell stdout is usually line buffered, while when you write to a file, it's usually full buffered.

After fork(), the child process will inherit the buffer, when you output to shell, the buffer is empty because of the new line \n, but when you output to a file, the buffer still contains the content, and will be in both the parent and child's output buffer, that's why hello is seen twice.

You can try it like this:

int main() {    printf("hello");    //Notice here without "\n"  if(fork()==0)      printf("world\n");    exit(0);  }  

You will likely see hello twice when output to shell as well.


This answer after Yu Hao 's answer . He already explain a lot .

main() {    printf("hello\n");    fflush(stdout);//flush the buffer  if(fork()==0)      printf("world\n");    exit(0);  }  

Then you can get the right output.