int main(void) {
printf("abc");
fork();
return 0;
}
Output of this code is :
abcabc
Why is it printing twice, even when fork system call is after the printf statement?
int main(void) {
printf("abc");
fork();
return 0;
}
Output of this code is :
abcabc
Why is it printing twice, even when fork system call is after the printf statement?
Because stdout
is buffered, often line-buffered. And in your program the buffer is flushed only at exit
time, or when returning from main
(and that happens "twice" when fork
don't fail).
Try adding fflush(NULL);
before the fork();
(which you should almost always do)
BTW, you should always keep the result of fork
and handle three cases: fork
failure, in child, in parent.
So fork
is behaving as it should, but printf
has not the naive immediate side-effect you imagine: it is buffering so the real output may happen latter. You'll also observe the buffering by replacing fork()
with sleep(15)
(the output happening at exit
time, or at end of main
, so after the sleep
, and for 15 seconds your program won't apparently output anything)
You might also use strace(1) to understanding what system calls are happening...