1

"When we call fork() on a process and its child is created, it is said that the point of execution starts from the point next to the fork() call in both the processes. But when I checked,

main() {
    printf("hello");
    val =fork();
    if(val==0){
        printf("child");
    }
    if(val>0){
        printf("parent");
    }
}

This program printed hello also twice. I am a little confused. Please help me out.

whoan
  • 8,143
  • 4
  • 39
  • 48
Dedeepya
  • 11
  • 2
  • possible duplicate of [printf anomaly after "fork()"](http://stackoverflow.com/questions/2530663/printf-anomaly-after-fork) – whoan Nov 20 '14 at 12:43
  • amongst other problems with the code, this line: val =fork(); should be PID_t val =fork(); and have the #include for the definition of PID_t – user3629249 Nov 20 '14 at 16:59
  • this second print of hello is because the output is buffered and the buffer had not been emptied, by either a '\n' at the end of the hello string or by the initial printf being followed by fflush(stdout); So the hello is still in the output buffer – user3629249 Nov 20 '14 at 17:02

1 Answers1

2

When you do printf("hello");, the output is line buffered for STDOUT which is not flushed. Now when the buffer still containing data, fork() call makes both parent and child process inherit data present in the buffer making it print twice.

Ideally you should be flushing the standard output as below:

printf("hello");
fflush(stdout);
fork();  
Sunil Bojanapally
  • 12,528
  • 4
  • 33
  • 46