this question has answer here:
- printf anomaly after “fork()” 3 answers
int main(void) { printf("abc"); fork(); return 0; } output of code :
abcabc why printing twice, when fork system call after printf statement?
because stdout buffered, line-buffered. , in program buffer flushed @ exit time, or when returning main (and happens "twice" when fork don't fail).
try adding fflush(null); before fork(); (which should do)
btw, should keep result of fork , handle three cases: fork failure, in child, in parent.
so fork behaving should, printf has not naive immediate side-effect imagine: buffering real output may happen latter. you'll observe buffering replacing fork() sleep(15) (the output happening @ exit time, or @ end of main, after sleep, , 15 seconds program won't apparently output anything)
you might use strace(1) understanding system calls happening...
Comments
Post a Comment