0

我有以下程序:

#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) 时,它会复制标准输出并关闭它。这样 execlp 将写入最低值描述符(这是我的管道,因为它关闭并复制了标准输出)。我哪里错了?

ps 我用 g++ 编译

4

1 回答 1

0

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

于 2013-12-16T05:41:19.070 回答