0
我正在使用dup2()
,pipe()
和fork()
来处理其他输入的命令。 ls
的输出正确传递到cat
,终端显示输出,但不会停止接收输入。换句话说,猫不会终止,所以我可以继续打字。exec()在与dup2一起使用时不会终止
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
int main() {
int pipefd[2], child_pid, grand_child;
pipe(pipefd);
child_pid = fork();
if (child_pid) {
waitpid(child_pid, NULL, 0);
/* Parent */
grand_child = fork();
if (!grand_child) {
dup2(pipefd[0], STDIN_FILENO);
close(pipefd[0]);
close(pipefd[1]);
execlp("cat", "cat", NULL);
} else {
waitpid(grand_child, NULL, 0);
}
} else {
/* Child */
dup2(pipefd[1], STDOUT_FILENO);
close(pipefd[1]);
close(pipefd[0]);
execlp("ls", "ls", NULL);
}
return 0;
}
也许问题是你在执行'ls'之前关闭'pipefd'? 'cat'也一样。 – theoden
请注意,在开始下一个流程之前等待管道中的第一个孩子完成操作是错误的做法。它强制线性/顺序执行,而不是允许并行/并发执行。如果管道中的第一个进程产生了太多的数据以致于它被阻塞,等待下一个进程读取一些数据,但是由于第一个进程尚未完成,下一个进程未启动,它也可能遇到阻塞。 –