9

If after a fork() is called the program should continue from the first instruction following the fork, why then the word START gets printed two times?

#include<stdio.h>
#include<unistd.h>

int main(){
        int pid;
        printf("START...");
        pid = fork();
        printf("%d: I've got %d\n", getpid(), pid);
        return 0;
}

For example a possible output is:

START...605: I've got 606

START...606: I've got 0

Yu Hao
  • 119,891
  • 44
  • 235
  • 294

1 Answers1

7

Because you didn't flush the output buffer and so the text exists in both parent and child's output buffer after the fork().

Add fflush(stdout); after the first printf() and see the difference.

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • You can also add newline ('\n') to the end of the string and the buffer should be flushed. – ciamej Apr 19 '16 at 14:02
  • @ciamej Yes, however that will give (slightly) different output. – trojanfoe Apr 19 '16 at 14:02
  • @SergeyA I didn't know it was a dupe. Also why haven't you asked the same question of dasblinkenlight? – trojanfoe Apr 19 '16 at 14:16
  • @SergeyA If you believe it's a dupe then simply mark the question, rather than engaging me in conversation. – trojanfoe Apr 19 '16 at 14:19
  • I did. And full disclosure - not the downvoter either. I also believe in discussion - may be I am missing something and your answer adds details which are missing in the dupe? – SergeyA Apr 19 '16 at 14:19
  • @SergeyA I'm just new to C. I didn't even know flushing buffers was a thing. Why is it a dupe? –  Apr 19 '16 at 14:20
  • I didn't ask the question, so you should direct that comment to person that did. Many people answer duplicate questions because they don't bother checking or think the answer will be localised to the question or simply want to help with that particular issue. That includes both you and SergeyA very recently, so lets stop with the hypocrisy, shall we. – trojanfoe Apr 19 '16 at 14:51