【问题标题】:Closing pipe, dup2, file descriptors in C?在C中关闭管道,dup2,文件描述符?
【发布时间】:2012-02-02 04:24:55
【问题描述】:

我正在运行一个管道程序。 我要运行的命令是 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);

编辑:你说得对,致命错误,我在争论中打错了

谢谢,看来我只需要关闭父级中的管道[1]

【问题讨论】:

    标签: c io fork pipe dup2


    【解决方案1】:

    父进程也需要在两次cmd调用后关闭管道的两端。

    【讨论】:

      猜你喜欢
      • 2014-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多