![](/img/trans.png)
[英]Cannot get correct output from program redirected via pipe C++ (Windows)
[英]execlp() output cannot be redirected to stdout with pipe
我有以下程序:
#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)。 我哪里错了?
ps我用g ++编译
我设法通过将stdout
指向文件(描述符)来解决此问题,然后在父进程中打开并从中读取execlp
的输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.