您的位置:首页 > 其它

利用管道获取控制台程序的标准输出

2015-01-22 21:35 274 查看
1.该程序调用控制台程序hello.exe,通过管道获取到hello.exe的标准输出数据,并打印到当前程序的标准输出。

#include <Windows.h>
#include <iostream>
#include <string>

using namespace std;

void invoke(string exe);

int main(int argc, char* argv[])
{
string exe = "hello.exe";
invoke(exe);
return 0;
}

void invoke(string exe)
{
SECURITY_ATTRIBUTES saPipe;
saPipe.nLength = sizeof(SECURITY_ATTRIBUTES);
saPipe.lpSecurityDescriptor = NULL;
saPipe.bInheritHandle = TRUE;

HANDLE hReadPipe, hWritePipe;
BOOL bSuccess = CreatePipe(&hReadPipe,
&hWritePipe,
&saPipe,
0);
if(!bSuccess)
return ;

PROCESS_INFORMATION pi;
STARTUPINFO si;
memset(&si,0,sizeof(si));
si.hStdInput=hReadPipe;
si.hStdOutput=hWritePipe;
si.dwFlags=STARTF_USESTDHANDLES;
si.cb=sizeof(si);

if(CreateProcess(NULL,(char*)exe.c_str(),NULL,NULL,TRUE,0,NULL,NULL,&si,&pi))
{
CloseHandle(pi.hThread);
const int max = 500;
char buf[max] = {0};
DWORD dw;

if(ReadFile(hReadPipe,buf,max-1,&dw,NULL))
{
cout<<buf<<endl;
// ZeroMemory(buf,max);
}

CloseHandle(pi.hProcess);
}

CloseHandle(hReadPipe);
CloseHandle(hWritePipe);
}
输出结果为:



2. hello.exe的主代码

#include <stdio.h>

void main()
{
printf("hello!\n");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: