Content written before fork() present in output twice

a 夏天 提交于 2020-01-15 11:24:53

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!