我正在运行一个做管道的程序。我要运行的命令是 ls | 猫。
int cmd(char** w, int* pipe, int action){
... some code up here
...
int fd;
if(child_pid == 0) {
if (pipe != 0) {
if (action == 0){
fd = dup2(pipe[0], STDIN_FILENO);
close(pipe[0]);
close(pipe[1]);
//close(fd);
}
else if (action == 1){
fd = dup2(pipe[1], STDOUT_FILENO);
close(pipe[0]);
close(pipe[1]);
//close(fd);
}
}
execvp(w[0], w);
printf("Unknown command\n");
exit(0);
}
... some code down here
当我运行代码时,命令 ls | cat 运行良好,只是 cat 没有结束(即管道没有关闭,只是等在那里什么都不做)。我认为这是因为我没有关闭流或其他东西,但我对 C/IO 不够熟悉,无法确定。我这样做对吗?
运行这个函数的代码就像
int fd[2];
int p = pipe(fd);
cmd(w, fd, 1);
cmd(w, fd, 0);
编辑:你说得对,致命错误,我在争论上打错了
thxs,看起来我只需要关闭父级中的管道 [1]