1

The following two codes are compiled and executed using the gcc compiler code1:

    main()
    {
     printf("Before FORK\n");
     fork();
     printf("After FORK \n\n");
    }

code 2:

    main()
    {
     printf("Before FORK");
     fork();
     printf("After FORK \n\n");
    }

The code1 prints "Before FORK" statement once but the code2 prints the same twice. Please explain the reason behind that.

se7en
  • 87
  • 1
  • 3
  • 16
  • yes it's a duplicate, but unintentional – se7en Apr 11 '14 at 07:57
  • 1
    I did not assume that you *intentionally* post a duplicate question! But this has been asked and answered frequently, and all I did was to Google for "printf fork" :-) – Martin R Apr 11 '14 at 07:59
  • 1
    In my opinion best answer for this was givven [here](http://stackoverflow.com/q/22008504/2549281) by David Schwartz – Dabo Apr 11 '14 at 09:34

1 Answers1

5

stdout is line-buffered by default when associated with a terminal. In example 2, add fflush(stdout) after the first printf to flush stdout.

ouah
  • 142,963
  • 15
  • 272
  • 331