我已成功将一个命令的输出输送到另一个命令的输入中,然后将第二个命令的输出显示到屏幕上。

我想通过三个连续的命令来执行此操作。 (实际上,最终我想在运行时传递到程序中的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的乞讨,但我再也看不到。

有任何想法吗?

有帮助吗?

解决方案

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top