[英]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.