我需要创建一个C程序来使用exec和未命名管道模拟此命令:
ls | sort | wc -l
但是我该怎么做呢?我才刚刚开始研究管道,我已经尝试过非常糟糕的
int main( int argc, char** argv )
{
int fd1[2], fd2[2],fd3[2], pid;
createPipe(fd1);
createPipe(fd2);
createPipe(fd3);
pid=babyMaker();
if (pid == 0)
{
dup2(fd2[0],0);
dup2(fd3[1],1);
execlp("wc","wc","-l",NULL);
}
pid=babyMaker();
if (pid == 0)
{
dup2(fd2[1], 1);
dup2(fd1[0], STDIN_FILENO);
execlp("sort", "sort", NULL);
}
pid=babyMaker();
if (pid == 0)
{
dup2(fd1[1], 1);
execlp("ls", "ls", "-la", NULL);
}
char string[BUFFER_SIZE];
int bytesReaded=read(fd3[0],string,BUFFER_SIZE);
string[bytesReaded-1]=0;
printf("%sn",string);
wait(NULL);
return 0;
}
编辑:添加了我的代码
您需要使用以下方法关闭每个操作中未使用的文件描述符:close(fd[0]);