Why output is different between to shell and to a file

bash, c, fork, unix

Solution

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.

Problem

Consider the following program. ``` main() { printf("hello\n"); if(fork()==0) printf("world\n"); exit(0); } ``` Compiling this program using `./a.out` gives the following Output: ``` hello world ``` compiling this program using `./a.out > output` gives the output in the file called 'output' and appears to be like this: ``` hello hello world ``` Why is this so?

Original source