execlp()输出无法使用管道重定向到stdout

时间:2013-10-20 07:48:18

标签: c++ linux exec fork parent-child

我有以下程序:

#include<iostream>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>

using namespace std;

int main()
{
  int p[2];
  int code;
  pid_t pid;
  if(-1==(pipe(p)))
  {
    cout<<"Pipe error!"<<endl;
    return 1;
  }
  if(-1==(pid=fork()))
  {
    cout<<"Fork error!"<<endl;
    return 1;
  }
  if(pid==0)
  {
     dup2(p[1],1);//duplicates stdout?
     close(p[0]);//closes reading end
     execlp("grep","grep","/bin/bash","/etc/passwd",NULL);
     return 1;
  }
  else
  {
    cout<<"works so far"<<endl;
    wait(&code);
    cout<<"Doesn't get here"<<endl;
    //how do i read from the pipe to print on the screen what execlp wanted to ?
  }
return 1;
}

我想重新定位管道中的execlp输出,以便父级可以读取它并自行打印它。 我知道execlp会覆盖子进程并将其打印到stdout本身,但是我需要父进程来执行此操作。

据我所知,到目前为止,当我做dup2(p [1],1)时,它复制了stdout并且它也关闭了它。这样execlp就会写入最低值的描述符(因为它关闭并复制了stdout,这就是我的管道)。我哪里错了?

P.S。我用g ++编译

1 个答案:

答案 0 :(得分:0)

我设法通过将stdout复制到文件(描述符)来解决此问题,然后在父进程中打开并从中读取execlp的输出。

相关问题