Why it is printing two "Hi" in the above program? Is fork() call compiler dependent?
Asked
Active
Viewed 44 times
2
-
3Remember that output to `stdout` (which `printf` uses) is *line buffered*, that means that the output will be flushed either when the buffer is full, when there is a newline in the output, or when `stdout` is closed (which happens at process exit). Guess what happens first in your case. – Some programmer dude Jan 25 '15 at 07:56
-
2@JoachimPileborg actually stdio buffering as a bit more [complex](http://stackoverflow.com/questions/3723795/is-stdout-line-buffered-unbuffered-or-indeterminate-by-default). Yet the baseline is the same - fork creates exact clone of the process including any buffered data awaiting flush. – Nick Zavaritsky Jan 25 '15 at 08:49
1 Answers
2
I think your question has been answered in the comments. But all the same, the child process basically inherits the buffer of the parent. As far as I know, the stdout buffer doesn't print, as mentioned by Jochaim Pileborg, till either of buffer being full, newline in the printf, or stdout being closed.
In this case, none of them happen before the child process is created. Now the parent's buffer containing "Hi" is copied as such to the child's buffer. When both the parent and the child finishes execution, the stdout is closed, and hence the output is flushed from each. This results in your two "Hi".

arkarc
- 21
- 1