[英]Closing pipe, dup2, file descriptors in C?
我正在运行一个做管道的程序。 我要运行的命令是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,看起来我只需要关闭父级中的pipe [1]
在两次cmd
调用之后,父进程还需要关闭管道的两端。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.