Linux / C:将管道重定向到STDIN / STDOUT

时间:2014-03-16 03:24:29

标签: c linux pipe dup2

我在模拟shell脚本时遇到了麻烦" env | grep HOME"用C程序。我发现第29行的评论解决了这个问题,但我不确定为什么!我读到另一个问题,因为dup2()正在关闭孩子的fd,但是手册页并没有表明这一点。任何人都可以给我一个确定的理由并帮助我理解这种行为吗?谢谢!

#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main(void){
 pid_t childpid;
 int fd[2];
 if(pipe(fd) == -1){ /*setup a pipe*/
  perror("Failed to setup pipeline");
  return 1;
 }
 if((childpid = fork()) == -1){ /*fork a child*/
  perror("Failed to fork a child");
  return 1;
 }
 if(childpid == 0){ /*env is the child*/
  if(dup2(fd[1],STDOUT_FILENO)==-1)
   perror("Failed to redirect stdout of env");
  else if(close(fd[0] == -1)) /*close unused file descriptor*/
   perror("Failed to close extra pipe descriptors on env");
  else{
   execl("/usr/bin/env", "env", NULL); /*execute env*/
   perror("Failed to exec env");
  }
  return 1;
 }
 if(dup2(fd[0],STDIN_FILENO)==-1) /*grep is the parent*/
  perror("Failed to redirect stdin of grep");
 //else if(close(fd[1]==-1))
  //perror("Failed to close extra pipe file descriptors on grep");
 else{
  execl("/bin/grep", "grep", "HOME", NULL); /*execute "grep HOME"*/
  perror("Failed to exec grep");
 }
 return 1;
}

1 个答案:

答案 0 :(得分:2)

我发现了你的错误。这是适合我的出口。这是一个常见的错误:

...
        else if (close(fd[0]) == -1) /*close unused file descriptor*/
            ...
    else if(close(fd[1]) == -1)
    ...

您最初所做的是将文件描述符设置为关闭到布尔值fd[x] == -1,您想要做的是在{{1}的返回值中检查-1 }。

相关问题