【发布时间】:2023-02-02 22:34:30
【问题描述】:
我需要创建一个程序,在 shell 中使用两个管道和三个进程执行此命令:ls |排序 |格雷普河我所做的代码是这样的:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <signal.h>
#include <fcntl.h>
#include <string.h>
#include <sys/wait.h>
#define WRITE 1
#define READ 0
int main(int argc, char** argv)
{
int fd1[2],fd2[2];
pid_t pid1,pid2;
if( (pid1 = fork()) < 0)
{
perror("fork");
exit(-1);
}
if( pipe(fd1) < 0)
{
perror("pipe 1");
exit(-1);
}
if( pipe(fd2) < 0)
{
perror("pipe 2");
exit(-1);
}
if( pid1 == 0 )
pid2 = fork();
if(pid1>0)
{
close(fd2[READ]);
close(fd2[WRITE]);
close(fd1[READ]);
dup2(fd1[WRITE],STDOUT_FILENO);
close(fd1[WRITE]);
execlp("ls","ls",NULL);
perror("ls");
exit(-1);
}
if(pid2>0)
{
close(fd1[WRITE]);
dup2(fd1[READ],STDIN_FILENO);
close(fd1[READ]);
close(fd2[READ]);
dup2(fd2[WRITE],STDOUT_FILENO);
close(fd2[WRITE]);
execlp("sort","sort",NULL);
perror("sort");
exit(-1);
}
if(pid2==0)
{
close(fd1[READ]);
close(fd1[WRITE]);
close(fd2[WRITE]);
dup2(fd2[READ],STDIN_FILENO);
close(fd2[READ]);
execlp("grep","grep","r",NULL);
perror("grep");
exit(-1);
}
}
可能我对这两个管道的通信有误,因为我今天才知道它们是如何工作的。很抱歉,如果我弄错了一些关于管道的重要事情。我希望有人可以帮助我解决这个问题并解释我的错误。谢谢。
【问题讨论】:
-
你是什么意思“在壳中”?您正在做管道工作而不是使用外壳。如果你真的做想运行一个 shell 命令,查看 system 这将使你的程序变得微不足道