问题
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?
回答1:
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
回答2:
The 'A' is stored in a buffer and flushed by both processes when they exit.
来源:https://stackoverflow.com/questions/26162492/content-written-before-fork-present-in-output-twice