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?

Vishwadeep Singh
  • 1,043
  • 1
  • 13
  • 38

1 Answers1

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

bwegs
  • 3,769
  • 2
  • 30
  • 33