首页 > 解决方案 > 将多个语句连接在一起仅执行第一个命令

问题描述

编辑问题的一半已修复,并且已对问题进行了编辑以反映该修复。我仍然只看到它在一系列管道中执行第一个命令。

我被困在我从头开始制作的外壳中的最后一件事上。我希望能够解析命令"finger | tail -n +2 | cut -c1-8 | uniq | sort",我认为我很接近。我现在所拥有的,当将该行作为字符串数组给出时,仅执行“手指”部分。

这是代码中无法正常工作的部分,我已将其缩小为仅此 for 循环和之后的部分:

mypipe[2];
//start out with stdin
oldinfd = 0;


   //run the beginning commands. connect in/out of pipes to eachother.
   for(int i = 0; i < max; i++){

      pipe(mypipe);

      processline(commands[i], oldinfd, mypipe[1]); //doesn't wait on children

      close(mypipe[1]);

      oldinfd = mypipe[0];

   }

   //run the final command, put output into stdout
   processline(commands[max], oldinfd, 1);  //waits on children

   ...

这个循环运行程序,最终应该是这样的:

标准输入 -> [0]管道[写入] -> [读取]管道[写入] -> ... ->[读取]管道[1] -> 标准输出

我的 processline 函数接收一行('finger')并execs它。例如,processline("finger", 0, 1)运行finger没有缺陷的命令。出于这个问题的目的,假设 processline 完美运行,我遇到的麻烦是我如何使用管道以及它们的写入和读取端。

同样通过打印声明,我已确认将正确的单词发送到正确的部分。(for 循环接收“finger”、“tail -n +2”、“cut -c1-8”和“uniq”,而最后一行接收的 commands[max] 是“sort”)。

标签: cshellpipe

解决方案


推荐阅读