c - Linux/C : Redirecting Pipes to STDIN/STDOUT

标签 c linux pipe dup2

我在用 C 程序模拟 shell 脚本“env | grep HOME”时遇到了问题。我发现注释掉第 29 行解决了这个问题,但我不太确定为什么!我在另一个问题上读到,这是因为 dup2() 正在关闭 child 的 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;
}

最佳答案

我发现了你的错误。这对我来说是正确的。这是一个常见的错误:

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

您最初所做的是将文件描述符设置为关闭 fd[x] == -1 的 bool 值,而您想要做的是检查 - 1close()的返回值中。

关于c - Linux/C : Redirecting Pipes to STDIN/STDOUT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22432578/

相关文章:

filter - Angular 2 个连续管道

c++ - Hpux C程序中__(两个下划线)代表什么

c - 如何取消引用二维整数数组?

Python、管道和命令行中的 "-c"选项

c - echo {1..50..2} 而不是管道进入 C 中的另一个程序

linux - linux不能用分号设置环境变量

c - 在 Makefile 中运行 unix 命令以解析文本并将其传递给链接行作为定义 -D

c - 如果更喜欢使用 -ffast-math,则 double 的良好标记值

python - 了解 Ubuntu 上的 Django 版本

linux - 尽管 if 语句中有退出代码,如何保持 for 循环