如何在自定义shell中实现管道



我正试图在linux中实现一个自定义shell,但我被困在管道实现上,通过管道实现,一个命令的输出将成为另一个的输入。根据我在网站上读到的内容,stdin和stdout对于不同的进程是分开的。

->按照这种方法,我将子进程的输出stdout重定向到写管道末端,然后执行ls命令。

->在父进程中,我将其stdin重定向到读取管道末端,并在执行排序命令之后(假设它将从管道获取输入(但是下面所附的代码没有给出任何输出。请告诉我原因是什么。我需要多生几个孩子吗?为什么?如果命令是ls|sort|grep"q1"?如果有多个管道,我该如何处理?我已经附上了代码以及

#include <iostream>
#include <unistd.h>
#include <string.h>
#include <cstring>
#include<sys/wait.h>
#include <sys/types.h>
#pragma warning(disable : 4996)
using namespace std;
int main()
{
int fd[2];
pipe(fd);
pid_t p1;
p1=fork();
int temp;
if(p1==0) //child
{
cout << "CHILD " << endl;
dup2(fd[1],STDOUT_FILENO);  //ouput directed to writing end of pipe
close (fd[1]);
close(fd[0]);
execlp("/bin/ls", "/ls" ,NULL);
}

else
{
wait(NULL);
cout << "Parent" << endl;
dup2(fd[0],STDIN_FILENO);  //input directed to reading end
close(fd[0]);
close (fd[1]);
execlp("/bin/sort","/sort",NULL);
cout <<"NOT CORRECT" << endl;
}

return 0;
}

在子进程的if块中,可以删除以下行:

close (fd[1]);

在子进程中,您将在管道的写入端对其进行写入,那么为什么要关闭该端呢?

类似地,您应该删除父进程的else块中的这一行:

close(fd[0]);

同样,您将需要在父进程中读取管道的末尾,所以它应该保持打开状态。

至于多个管道,我不知道如何修复那个部分。

最新更新