【问题标题】:trouble pipeline three commands "dmesg|sort|more" c++麻烦管道三个命令“dmesg|sort|more”c++
【发布时间】:2010-10-14 00:39:19
【问题描述】:

我已成功地将一个命令的输出通过管道传输到另一个命令的输入,然后将第二个命令的输出显示到屏幕上。

我想用三个连续的命令来做到这一点。 (实际上最终我想在运行时将 N 个命令传递给程序。

这是我将三个命令连接在一起的尝试。

更新:我更新了我的问题以反映我最近的尝试。

    #include <string.h>
    #include <fstream>
    #include <iostream>
    #include <unistd.h>
    #include <stdio.h>
    #include <sys/wait.h>
    #include <sys/types.h>
    using namespace std;

    int main(int argc, char * argv[])
    {
             pid_t pid;
        int pfd[2];
        char* prgname = NULL;
        if(pipe(pfd) == -1)
        {
                perror("error on pipe call");
                return(1);
        }
        for(int j = 0;j<numberOfCommands;j++)
        {
                cout<<commands[j]<<"_"<<endl;
        }
        pid = fork();
        if(pid == 0){//child process
                close(pfd[0]); //close read end of pipe
                dup2(pfd[1],1);//connect the pipes
                close(pfd[1]);//close extra file descriptors
                prgname = (char*)"dmesg"; //commands[0];//first command
                execlp(prgname, prgname, 0);//Load the program
        }
        else
        {
                int pfd2[2];
                if(pipe(pfd2) == -1)
                {
                        perror("error on pipe call 2");
                        return(1);
                }
                pid = fork();
                if(pid == 0)//child
                {
                        close(pfd[1]);
                        dup2(pfd[0],0);
                        close(pfd[0]);
                        close(pfd2[0]);
                        dup2(pfd2[1],1);
                        close(pfd2[1]);
                        prgname = (char*)"sort";
                        execlp(prgname,prgname,0);
                }
                else
                {
                close(pfd2[1]); //close the write end of the pipe
                dup2(pfd2[0],0);//connect the pipes
                close(pfd2[0]); //close extra file descriptor
                prgname = (char*)"more"; //commands[1];//now run the second command
                execlp(prgname, prgname, 0);//Load the program
                }
        }
        return 0;
}

为简单起见,我对所有值进行了硬编码。 该程序显示应该是“dmesg|more”的输出,但不执行排序部分,然后冻结。我在左下角看到了 dmesg 的乞求和更多内容,但我再也看不到了。

有什么想法吗?

【问题讨论】:

  • 您认为dmesg | sort | moredmesg | more 有何不同?我刚刚运行它,消息似乎按排序顺序出现。还有,你确定不只是在等你按空格键吗?
  • 好吧,我的全部意图是运行 sort-f。它确实以不同的顺序输出它们。不,这不仅仅是在等我。当我通过常规提示运行更多命令时,它会在左下角显示更多,而在运行程序时则不会。

标签: c++ pipe fork dup2


【解决方案1】:

pipe(2) 只为 1 个管道提供 2 个文件描述符。第三个文件描述符 (pfd[2]) 是垃圾文件,永远不会被初始化。如果要创建一个包含 3 个命令的管道,则需要调用 pipe() 两次以获得两个管道:一个用于连接第一个和第二个进程,一个用于连接第二个和第三个进程。

【讨论】:

  • 我更新了我的答案以反映我最近使用两个管道的尝试。
猜你喜欢
  • 2011-05-06
  • 2016-03-04
  • 2011-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多