在项目中用到了Windows进程通信 ,需要用管道读子进程的标准输入,输出,于是研究了MSDN上的相关代码
代码源地址:https://msdn.microsoft.com/en-us/library/windows/desktop/ms682516(v=vs.85).aspx
ps :a代码中需要注意的是在CreateChildProcess中通过
siStartInfo.hStdErro=g_hChildStd_OUT_Wr;
siStartInfo.hStdOutput=g_hChildStd_OUT_Wr;
siStartInfo.HStdInput-g_hChildStd_IN_Rd;
通过以上代码,将子进程的标准错误输出,标准输出,标准输入都重定向为管道,这些管道是在主进程中创建的,可以被子进程继承!
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>
#define BUFSIZE 4096
HANDLE g_hChildStd_IN_Rd = NULL;
HANDLE g_hChildStd_IN_Wr = NULL;
HANDLE g_hChildStd_OUT_Rd = NULL;
HANDLE g_hChildStd_OUT_Wr = NULL;
HANDLE g_hInputFile = NULL;
void CreateChildProcess(void);
void WriteToPipe(void);
void ReadFromPipe(void);
void ErrorExit(PTSTR);
int _tmain(int argc, TCHAR *argv[])
{
SECURITY_ATTRIBUTES saAttr;
printf("\n->Start of parent execution.\n");
// Set the bInheritHandle flag so pipe handles are inherited.
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
// Create a pipe for the child process's STDOUT.
if (!CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0))
ErrorExit(TEXT("StdoutRd CreatePipe"));
// Ensure the read handle to the pipe for STDOUT is not inherited.
if (!SetHandleInformation(g_hChil