我的理解:
windows的匿名管道 在于 父进程和子进程之间创建,需要创建两个管道,一共四个HANDLE,还需要关掉两个
设父进程到子进程的管道为pipein,连接父进程的一端,HANDLE为wt,连接子进程的一端,HANDLE为rd
设子进程到父进程的管道为pipeout,连接父进程的一端,HANDLE为rd,连接子进程的一端,HANDLE为wt
父进程代码解析:
#include "stdafx.h"
#include <string>
#include <iostream>
#include <Windows.h>
int main(int argc, char **argv)
{
HANDLE hpipeInRd, hpipeInWt;
HANDLE hpipeOutRd, hpipeOutWt;
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = FALSE;
if (!CreatePipe(&hpipeOutRd, &hpipeOutWt, &sa, 0))
{
printf("stdout Create Pipe error!!!");
return 1;
}
if(!SetHandleInformation(hpipeOutRd, HANDLE_FLAG_INHERIT, 0))
{
printf("stdout SetHandleInformation !!!");
return 1;
}
if (!CreatePipe(&hpipeInRd, &hpipeInWt, &sa, 0))
{
printf("stdin Create Pipe error!!!");
return 1;
}
if (!SetHandleInformation(hpipeInWt, HANDLE_FLAG_INHERIT, 0))
{
printf("stdout SetHandleInformation !!!");
return 1;
}
TCHAR lpCommandLine[100] = _T("client");
PROCESS_INFORMATION pi;
ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
STARTUPINFO si;
ZeroMemory(&si, sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
si.hStdError = hpipeOutWt;
si.hStdOutput = hpipeOutWt;
si.hStdInput = hpipeInRd;
si.dwFlags |= STARTF_USESTDHANDLES;
int ret = CreateProcess(NULL, lpCommandLine, NULL, NULL,
TRUE, 0/*CREATE_NEW_CONSOLE*/, NULL, NULL, &si, &pi);
if (ret)
{
WaitForSingleObject(pi.hProcess, 2);
printf("child process is created!!!\n");
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
char buffer[100] = {0};
DWORD read;
HANDLE hstdin = GetStdHandle(STD_INPUT_HANDLE);
ReadFile(hstdin, buffer, sizeof(buffer), &read, NULL);
DWORD writeBytes;
WriteFile(hpipeInWt, buffer, strlen(buffer), &writeBytes, NULL);
DWORD readBytes;
memset(buffer, 0, sizeof(buffer));
ReadFile(hpipeOutRd, buffer, sizeof(buffer), &readBytes, NULL);
printf("msg from child process is: %s\n", buffer);
CloseHandle(hpipeInRd);
CloseHandle(hpipeInWt);
CloseHandle(hpipeOutWt);
CloseHandle(hpipeOutRd);
return 0;
}