在C中关闭管道,dup2,文件描述符?

问题描述:

我正在运行一个管道程序。 我想运行的命令是ls |猫。在C中关闭管道,dup2,文件描述符?

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 |除了猫没有结束(即管道不关闭,只是在那里等待什么都不做)之外,猫运行得很好。我认为这是因为我没有关闭流或其他东西,但我对C/IO不够熟悉。我做对了吗?

运行此函数的代码是一样

int fd[2]; 
int p = pipe(fd); 
cmd(w, fd, 1); 
cmd(w, fd, 0); 

编辑:你是对的,fatalerror,我在arguement

thxs拼写错误,貌似我只需要关闭管[1]中parent

父进程还需要关闭两个cmd调用后的管道两端。