Reputation: 47
I wrote the following C code:
#include<stdio.h>
int main(){
printf("A");
if(fork() == 0){
printf("B");
}
else{
printf("C");
}
}
The output I got is:
ACAB
I expected this code to print A only once.
Can anyone explain this output?
Upvotes: 1
Views: 78
Reputation: 59987
The 'A' is stored in a buffer and flushed by both processes when they exit.
Upvotes: 1
Reputation: 45654
Your error is not flushing the buffers before fork
-ing, thus both processes will write it.
Add this before fork()
:
fflush(0); // Flush all output-streams
Upvotes: 3