I encountered this in my school work and it didn't produce what I thought it should:
int main() {
printf("c");
fork();
printf("d");
}
I know there are several things that aren't good about this code (i.e. no parameters in main, no variable for the return value from fork, no return statement at the end, etc.), but this is how it was presented and it's not relevant to my question anyway.
This code produces the output:
cdcd
It was my understanding that when fork is called, both parent and child would resume/begin on the line after the fork call. Based on that, I would have expected the output to be:
cdd
Assuming, of course, that the fork call is successful. Can anyone explain to me why that "c" is printed a second time even though it's on the line before the fork call?
Thanks! M_MN
The reason you're seeing c
twice is that the fork()
duplicates the unprinted buffered output. You could flush the output stream before the fork()
:
fflush(stdout);
Or you could set stdout
to be unbuffered, but you should do this first, before calling printf()
the first time:
setvbuf(stdout, NULL, _IONBF, 0);