c - Unix 管道链延迟

标签 c linux unix pipe

我正在尝试为 3 个进程加上当前程序创建一个管道链,这样:

1 - 执行 P1 并将 P1 的输出发送到 P2 的输入

3 - 将 P2 的输出发送到 P3 的输入

4 - 在标准输出中显示 P3 的输出

5 - 将当前/主/驱动程序的标准输入传递给 P3 的输入

我正在使用 2 个管道。对于任务#5,主程序从 stdin 读取并写入 P3 读取的管道。

我已经设法让进程相互通信。然而,我注意到 P1 写入和 P2 在其 STDIN 上检测到此写入之间存在很大的延迟,即 P1 可能在 P2 检测到写入之前已经写入数百次并且在开始时错过了许多 P1 写入。我已经通过打印消息确认 P2 实际上是按时启动的,但是,它没有及时检测/读取输入(这是一个 Python 脚本循环:“for line in sys.stdin:”)

这是我的代码:

int pipe1[2];
int pipe2[2];
if (pipe(pipe1) < 0 || pipe(pipe2) < 0  )
{
    perror("Error: pipe");
}   


pid_t procIDC = fork();
if (procIDC == 0)
{       
    dup2(pipe2[0], 0);
    execv("procC", argv);           
}   
else
{       
    pid_t procIDB ;
    procIDB = fork();   

    if (procIDB == 0)
    {       
        dup2( pipe1[0], 0);  
        dup2( pipe2[1], 1);


        if (execl("/usr/bin/python", "/usr/bin/python", "./test.py", (char *)NULL) < 0)
        {
            perror("execl"); return 0;
        }
    }
    else
    {           
        pid_t procIDA = fork(); 
        if (procIDA ==0)
        {       
            dup2( pipe1[1], 1);
            execv("proc1", argv);       
        }   
        else
        {                   
            dup2( pipe2[1], 1);

            //print any input so it sends to p3
            ssize_t read;   
            char *inputLine = NULL;
            size_t len = 0;        
            while ((read = getline(&inputLine, &len, stdin)) != -1) 
            {
                printf(inputLine);
            }               
        }
    }

最佳答案

I noticed is there is a large delay between when P1 writes and when P2 detects this write on its STDIN

是的。您的问题大概是“为什么会有延迟”?

答案:stdio (大多数程序使用)检测到输出正在进入管道时使用全缓冲输出。

要防止缓冲,请使用 fflushsetvbuf .

一些补充阅读 here .

Actually, the fflush is obviously being done in the writing program

您没有向我们展示 fflush 的写作程序在里面。如果您有,我们可能会指出您的错误(fflush 提供帮助,如果操作正确的话)。

无论如何,查看正在发生的事情的一种方法是运行 strace -p <pid-of-writer> ,并在作者实际执行 write(2) 之后立即观察到这一点系统调用,读者得到它的输入。这将证明它实际上是在造成延迟的作者中缓冲。

这个:

setbuf(stdout, NULL);

不禁用缓冲。你真的需要调用setvbuf (或 fflush )。

关于c - Unix 管道链延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26707703/

相关文章:

c - 在尝试释放()之前确定结构成员是否具有有效数据

linux - RHEL 6.3(64 位): Install a package to a specific version of php

linux - 有用的 BASH 代码片段

与 select() 混淆 - stdout 从未准备好写入

shell - 执行脚本后如何恢复 shell 提示符

c - 在c中获取文件文本的行数

c - 从内核劫持系统调用

c++ - 制作结构数组?

c# - mono Process.Start 如何找到 bash?

c - 我如何在 C 中编写监视器代码?