fork()打印两次之前的语句 [英] Statement before fork() printing twice

查看:103
本文介绍了fork()打印两次之前的语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试fork()和重定向,以检查在父级中完成的重定向是否也适用于子级.我写了下面的简单程序

I was experimenting with fork() and re-direction to check whether the re-directions done in the parent apply to the child too. I wrote the following simple program

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>

int main ()
{
    freopen( "error.txt", "w+t", stdout ); // From now on, stdout = error.txt
    printf (" ERROR!  WHY DONT U UNDERSTAND?\n");
    if ( fork() == 0 ) 
    {   
        printf(" I AM CHILD\n");
        exit(0);
    }   
    else-
    {   
        printf (" EITHER I AM A PARENT OR SOMETHING GOT SCREWED\n");
    }   


    return 0;
}

我得到的输出(error.txt)是

ERROR!  WHY DONT U UNDERSTAND?
EITHER I AM A PARENT OR SOMETHING GOT SCREWED
ERROR!  WHY DONT U UNDERSTAND?
I AM CHILD

令人惊讶的是,即使ERROR! WHY DONT U UNDERSTAND?在两次调用fork()之前就出现了两次,但仍被 打印两次 .

Surprisingly, ERROR! WHY DONT U UNDERSTAND? is printing twice even though it appears much before the fork() is called and should only be printed once by the parent.

任何人都可以对此有所了解吗?

Can anyone shed some light on this?

推荐答案

由于reopen之后,流是非交互式的,因此它已被完全缓冲并且不会在'\n'上刷新.在调用fork之前,缓冲区仍然包含该消息,并且在fork之后,此缓冲的消息被复制(因为两个进程都拥有自己的stdout副本),然后被父级和子级都刷新.参见C标准的7.19.3部分.

Since after reopen the stream is non-interactive, it's fully buffered and doesn't flush on '\n'. Before fork is called the buffer still contains the message, and after fork this buffered message was duplicated (because both processes got their own copies of stdout) and then flushed by both the parent and the child. See part 7.19.3 of C standard.

您可以通过在fork之前调用fflush来避免这种行为.

You can avoid such behavior by calling fflush just before fork.

这篇关于fork()打印两次之前的语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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