0

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

我想用三个连续的命令来做到这一点。(实际上最终我想用在运行时传递给程序的 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 的乞求和更多内容,但我再也看不到了。

有任何想法吗?

4

1 回答 1

2

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

于 2010-10-14T00:45:26.113 回答