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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With