【问题标题】:C++ Shell multiple pipelines are not working?C++ Shell 多管道不工作?
【发布时间】:2019-05-28 15:09:55
【问题描述】:

我曾在 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

如果有任何见解/帮助,我将不胜感激。

谢谢转发。

【问题讨论】:

  • 旁白:5 级嵌套会导致代码不可读。考虑重构您的 execute 方法。
  • 以后会调查的。
  • 什么都没有是什么意思?喜欢程序立即退出还是继续运行?
  • @Quimby 应该解释一下,我的错。我刚刚在 shell 中执行程序后打印了状态。如果我正在执行 ls -l | grep 测试 | grep test2,然后我得到以下信息:-> 程序 test2 以状态码 256 结束。但是,程序继续运行,它可以接受我的输入。
  • 您在创建管道之前调用了dup2ReadPipe!请先致电pipe

标签: c++ linux shell unix


【解决方案1】:

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

  • 您没有关闭管道。 READPIPE, WRITEPIPE 文件描述符仍然是打开的,这让读者保持 跑步。 EOF 只有在所有写端都关闭时才被读取。
  • 在子节点中打开管道没有意义,无法将它们传递给下一个管道。
  • 在执行中间命令期间,有两个活动管道 - 读取左侧管道的末端作为输入。将右管道的末端写入输出。

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

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_ 应该忽略已经关闭/不存在的管道。关闭孩子很重要,否则孩子会保持自己的生命,因为它会阻塞left_pipe.read,这将等待left_pipe.write (由同一个孩子持有)结束写点东西。 p>

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

【讨论】:

  • 感谢您的反应。确实,它更具可读性。不知何故,我认为将其拆分为方法会更干净。明天我会调查并及时通知您。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-07
  • 2015-10-28
  • 2018-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多