在fork()之前写入的内容在输出中出现两次 [英] Content written before fork() present in output twice

查看:165
本文介绍了在fork()之前写入的内容在输出中出现两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下C代码:

#include<stdio.h>

int main(){
    printf("A");
    if(fork() == 0){
        printf("B");
    }
    else{
        printf("C");
    }
}

我得到的输出是:

ACAB

我希望此代码仅打印一次A.
谁能解释这个输出?

I expected this code to print A only once.
Can anyone explain this output?

推荐答案

您的错误未在fork -ing之前刷新缓冲区,因此两个进程都将其写入.

Your error is not flushing the buffers before fork-ing, thus both processes will write it.

fork()之前添加此内容:

fflush(0); // Flush all output-streams

这篇关于在fork()之前写入的内容在输出中出现两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆