C++ Shell 多管道不工作?

标签 c++ linux shell unix

我曾在 C++ 中处理过管道,并且设法让单个管道正常工作。我正在努力让多个管道工作。我不知道到底哪里出了问题。

我用来测试单个管道的示例:

ls -l | grep test

我用来测试多个管道的示例:

ls -l | grep test | grep test2

第一个命令对我来说很好用。 然而,第二个命令对我来说几乎没有任何作用。

编辑 1-6-2019:我将尝试使用此伪代码

left_pipe = NULL
right_pipe = NULL

for each command:

    if not last:
        right_pipe = pipe()

    fork():
        child:
            if left_pipe is not NULL:
                STDIN = left_pipe.read
            if right_pipe is not NULL:
                STDOUT = right_pipe.write
            left_pipe.close_W()
            right_pipe.close_R()
            execute()
            left_pipe.close_RW()
            //Move right pipe to the left side for the next command
            left_pipe = right_pipe
end

我将不胜感激任何见解/帮助。

感谢转发。

最佳答案

正如@AndyG 所说,请重构代码,代码困惑、冗余且容易出错。以下是这些错误:

  • 你没有关闭管道。 READPIPEWRITEPIPE 文件描述符仍然打开,这让读者 运行。 EOF 只有在所有写端都关闭时才可读。
  • 在 child 身上打开管道没有意义,没有办法将它们传递给下一个。
  • 在执行中间命令期间,有两个事件管道 - 读取左侧管道的末端作为输入。将右管道的末尾写为输出。

在伪代码中你想做这样的事情:

left_pipe = NULL
right_pipe = NULL

for each command:

    if not last:
        right_pipe = pipe()

    fork():
        child:
            if left_pipe is not NULL:
                STDIN = left_pipe.read
            if right_pipe is not NULL:
                STDOUT = right_pipe.write
            left_pipe.close_W()
            right_pipe.close_R()
            execute()
            left_pipe.close_RW()
            //Move right pipe to the left side for the next command
            left_pipe = right_pipe
end

加上一些错误检查,close_ 应该忽略已经关闭/不存在的管道。关闭 child 很重要,否则 child 会保持自己活着,因为它会阻塞 left_pipe.read 等待 left_pipe.write ( 持有同一个 child )结束写点东西。

我希望您同意这也更具可读性。

关于C++ Shell 多管道不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56345205/

相关文章:

c++ - 从 UPDATE 查询中获取 'Cannot insert duplicate key'

c++ - 如何将 char 数组定义为常量?

python - 如何使用构造函数变量打开Python脚本

c++ - 创建共享库时发生核心转储

linux - 允许 aa-exec 临时用户访问文件夹

c++ - 初始化模板对象

android - 是否可以在 SO 库中公开 C API 以访问 Android JAVA 方法?

linux - 如何从 .t​​ar.gz 制作 .ubi 文件

linux - 使用 pipe 和 tee 命令获取在后台运行的命令的返回值

bash - 如何在tail -f上找到键的值