[英]execlp() output cannot be redirected to stdout with pipe
I have the following program: 我有以下程序:
#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;
}
I want to redirect the execlp output in the pipe so that the parent can read it and print it itself. 我想在管道中重定向execlp输出,以便父级可以读取它并自己打印。 I understand that execlp overwrites the child process and it prints to stdout itself, but i need the parent to do that.
我知道execlp会覆盖子进程,并且会打印到stdout本身,但是我需要父进程来执行。
From what i understand so far, when i do dup2(p[1],1) it duplicates the stdout and it closes it too. 根据我到目前为止的了解,当我执行dup2(p [1],1)时,它会复制stdout并将其关闭。 So that execlp would write to the lowest value descriptor (that being my pipe since it closed and copied stdout).
这样该execlp便会写入最低值描述符(这是我的管道,因为它关闭并复制了stdout)。 Where am i wrong ?
我哪里错了?
ps I compile with g++ ps我用g ++编译
我设法通过将stdout
指向文件(描述符)来解决此问题,然后在父进程中打开并从中读取execlp
的输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.