【问题标题】:execlp() output cannot be redirected to stdout with pipeexeclp() 输出不能用管道重定向到标准输出
【发布时间】:2013-10-20 07:48:18
【问题描述】:

我有以下程序:

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

附言我用 g++ 编译

【问题讨论】:

  • 注意:wait(code) 无效。您传递的是不确定的 int 变量的 value 而不是 int 变量的 address,因此您的编译器甚至不会编译它。如果是,请获取一个新的编译器。
  • 我错了,是wait(&amp;code);
  • 这已修复,我到达并打印“没有到达这里”没有问题,所以我不确定您的问题是什么。您甚至没有等待该管道的父进程结束,只是等待子进程终止。
  • 它只是挂在我身上。您还可以通过等待管道的父进程端来进一步解释您的意思吗?
  • 我在代码中添加了更多信息

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-04-26
    • 1970-01-01
    • 2013-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    • 2012-05-28
    • 1970-01-01
    相关资源
    最近更新 更多