为什么linux管道和标准输出不能一起工作

Why linux pipes and stdout from exec not working together?

本文关键字:不能 一起 工作 标准输出 linux 管道 为什么      更新时间:2023-10-16

我用linux管道写代码,不明白为什么只有printfs(1)或只有exec(2)进入父进程的输入。如果我注释exec,那么打印工作正常。如果取消注释,只显示"ls"输出

int main(void)
{
    int fd[2], pid;
    if (pipe(fd) != 0) return 1;
    if ((pid = fork()) == -1) return 1;
    if (pid == 0) // child
    {
        close( STDOUT_FILENO );
        dup2( fd[1], STDOUT_FILENO );
        close( fd[0] );
        close( fd[1] ); // */
        printf( "hellon" ); // (1)
        printf( "hello2n" );
        // execl( "/bin/ls", "ls", NULL ); // (2)
        printf( "exec not executedn");
    }
    else
    {
        close( STDIN_FILENO );
        dup2( fd[0], STDIN_FILENO );
        close( fd[0] );
        close( fd[1] );
        char buf[100];
        while( gets( buf ) != NULL )
            printf( "message: %sn", buf );
    }
}

exec注释时的输出:

消息:你好
消息:hello2
消息:exec not executed

当exec没有注释时:

信息:filt1
信息:filt1.d
…其他文件
信息:makefile
信息:objects.mk

默认情况下,stdio完全缓冲输出到流,除非它写入终端(stderr除外,它是未缓冲的)。因此,管道的输出正在被缓冲。

当你调用execl()时,当前进程的内存被丢弃,并被你正在加载的程序所取代。这将导致工作室输出缓冲区被丢弃,因此它们永远不会被写入管道。

简单的解决方法是先呼叫fflush(stdout);,再呼叫execl()