gpt4 book ai didi

c++ - 故障管道三个命令 "dmesg|sort|more"c++

转载 作者:行者123 更新时间:2023-11-28 03:55:03 24 4
gpt4 key购买 nike

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

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

这是我尝试将三个命令流水线化在一起。

更新:我更新了我的问题以反射(reflect)我最近的尝试。

    #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() 以获得两个管道:一个用于连接第一个和第二个进程,一个用于连接第二个和第三个过程。

关于c++ - 故障管道三个命令 "dmesg|sort|more"c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3929179/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com