C++壳牌多个管道不起作用?

C++ Shell multiple pipelines are not working?

本文关键字:管道 不起作用 C++      更新时间:2023-10-16

我在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才是只读的。
  • 在孩子身上打开管道没有意义,没有办法将它们传递到下一个管道上。
  • 在执行中间命令期间,有两个活动管道 - 读取左管道的末端作为输入。将右管道的末端写入为输出。

在伪代码中,您希望执行以下操作:

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(由同一个孩子持有)结束写东西。

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