0
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?

Ideone link

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
BuggerNot
  • 438
  • 1
  • 6
  • 20

1 Answers1

6

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

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • 2
    The `fork()` copies the whole process, even the buffer containing the unprinted `abc`. When they both exit, each process flushes its buffer with the unprinted `abc`, and so you see it twice because each process is printing it when it's being flushed. – e0k Jan 24 '16 at 17:06