Why the output differs from shell to file

Consider the following program.

main() { printf("hello\n"); if(fork()==0) printf("world\n"); exit(0); } 

Compiling this program with ./a.out yields the following output:

 hello world 

compiling this program with ./a.out > output produces a result in a file called 'output' and looks like this:

 hello hello world 

Why is this so?

+4
source share
2 answers

Because when you go to shell stdout , as a rule, a string is buffered, and when you write a file, it is usually filled with a buffer.

After fork() child process inherits the buffer when you exit the shell, the buffer is empty due to the new line \n , but when you exit the file, the buffer still contains the contents, and will be in the parent and child output buffer, therefore hello displayed twice.

You can try this as follows:

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

You will probably see hello twice when you also exit the shell.

+15
source

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

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

Then you can get the correct conclusion.

+3
source

Source: https://habr.com/ru/post/1495094/


All Articles