Linux/C:将管道重定向到STDIN/STDOUT [英] Linux/C: Redirecting Pipes to STDIN/STDOUT

查看:131
本文介绍了Linux/C:将管道重定向到STDIN/STDOUT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在用C程序模拟shell脚本"env | grep HOME"时遇到了麻烦.我发现注释掉第29行可以解决此问题,但是我不确定为什么!我读到另一个问题,这是因为dup2()正在关闭子级中的fd,但手册页并未指出这一点.谁能给我一个明确的理由并帮助我理解这种行为?谢谢!

I was having trouble with simulating the shell script "env | grep HOME" with a C program. I found that commenting out line 29 solved this problem, but I'm not really sure why! I read on another question that it was because dup2() was closing the fd in the child, but the man page doesn't indicate that. Can anyone give me a definitive reason and help me understand this behavior? Thank you!

#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;
}

推荐答案

我发现了您的错误.这是适合我的退出方式.这是一个常见的错误:

I found your bug. Here's what exits properly for me. It's a common mistake:

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

您最初所做的是将文件描述符设置为接近fd[x] == -1的布尔值,而您想要做的就是检查close()的返回值中的-1.

What you were doing originally was setting the file descriptor to be closed to the boolean value of fd[x] == -1, and what you wanted to do was check for -1 in the return value of close().

这篇关于Linux/C:将管道重定向到STDIN/STDOUT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆