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.
source share