我想知道这个管道的实现有什么问题.我正在try 实现以下命令ls |grep "main-pipe" |wc
.然而,它进入了无限循环,我不明白为什么它不能从标准输入中读取.我还判断了在第二个过程中(对于grep
)从ls
获得的输出是否正确以及它是否正确.我想不出是什么导致了无限循环.你能帮我拿一下吗?
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
int main(int argc, char* argv[]) {
if (argc > 1) {
printf("Please don't provide additional arguments.\n");
exit(1);
}
int pipe1[2];
pipe(pipe1);
int pid = fork();
if (pid == 0) {
// Write to the write end of the pipe
close(1);
dup(pipe1[1]);
close(pipe1[1]);
close(pipe1[0]);
execlp("ls", "ls");
}
wait(0);
int pipe2[2];
pipe(pipe2);
pid = fork();
if (pid == 0) {
close(0);
dup(pipe1[0]);
close(pipe1[0]);
close(pipe1[1]);
close(1);
dup(pipe2[1]);
close(pipe2[0]);
close(pipe2[1]);
execlp("grep", "grep", "main-pipe", (char *)NULL);
}
wait(0);
close(0);
dup(pipe2[0]);
close(pipe1[0]);
close(pipe1[1]);
close(pipe2[0]);
close(pipe2[1]);
execl("wc", "wc");
exit(0);
}