C++ 故障管道三个命令“;dmesg“排序”更多;c++;

C++ 故障管道三个命令“;dmesg“排序”更多;c++;,c++,pipe,fork,dup2,C++,Pipe,Fork,Dup2,我已经成功地将一个命令的输出传输到另一个命令的输入中,然后将第二个命令的输出显示到屏幕上 我想用三个连续的命令来实现这一点。(实际上,我最终希望在运行时将N个命令传递到程序中 这是我尝试将三个命令流水线连接在一起 更新:我更新了我的问题以反映我的最新尝试 #include <string.h> #include <fstream> #include <iostream> #include <unistd.h>

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

我想用三个连续的命令来实现这一点。(实际上,我最终希望在运行时将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;
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
int main(int argc,char*argv[])
{
pid_t pid;
int-pfd[2];
char*prgname=NULL;
如果(管道(pfd)=-1)
{
perror(“管道调用错误”);
申报表(1);
}

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

我更新了我的答案,以反映我最近使用两个管道的尝试。你认为
dmesg | sort | more
dmesg | more
有何不同?我刚刚运行了它,消息似乎来自不管怎么说,它都是按排序顺序输出的。另外,你确定它不是在等你点击空格键吗?我的全部意图是运行sort-f。它确实为我以不同的顺序输出它们。不,它不仅仅是在等我。当我通过常规提示符运行more命令时,它会在左下角显示更多信息,当运行pro时但事实并非如此。