1
#include <stdio.h>
int num = 0;
int main(int argc, char*argv[]){
   printf("common line\n");  
   printf("%d", num); 
   int pid;
   pid = fork();
   if(pid == 0){       /*child*/
      num = 1;
   } else if(pid > 0){  /*parent*/
      num = 2;
   }
   printf("%d\n", num);
}

I above program, common line string is shown single time in output. But "0" is comming twice in the results.

Coming outputs:

common line
01
02

OR

common line
02
01

As per my understanding, 0 should come only once?

8
  • 1
    possible duplicate of About fork and printf/write
    – R Sahu
    Mar 10, 2015 at 18:54
  • You are printing it twice. Mar 10, 2015 at 18:55
  • 2
    You didn't flush it. Mar 10, 2015 at 18:57
  • 1
    When you fork, all data is duplicated in the child process. If you fork without flushing stdout, buffered data (the 0 here) is duplicated in the child process: a '0' is printed by both process when stdout is flushed AFTER forking. Mar 10, 2015 at 19:12
  • 1
    stdout is line buffered. you forked the line buffer too.
    – Jason Hu
    Mar 10, 2015 at 19:29

1 Answer 1

3

By adding a newline character at the end of your string you are implicitly flushing the output buffer before you fork. Your other option is to explicitly flush it with fflush(stdout). Otherwise when you fork(), both processes are just spitting out whatever was still left in the buffer beforehand (in your case the unflushed buffer still contains num from printf("%d", num)).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.