模拟 ls | 的 C 程序中的管道损坏 |排序 | wc -l
Broken Pipes in a C program that simulates ls | sort | wc -l
我需要创建一个 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("%s\n",string);
wait(NULL);
return 0;
}
编辑:添加了我的代码
您需要使用以下方法关闭每个操作中未使用的文件描述符:
关闭(fd[0]);
我需要创建一个 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("%s\n",string);
wait(NULL);
return 0;
}
编辑:添加了我的代码
您需要使用以下方法关闭每个操作中未使用的文件描述符: 关闭(fd[0]);