概述
1.匿名管道 (主要用于父子进程的通信)
父进程
#include <iostream>
#include <windows.h>
using namespace std;
int main(int argc, char *argv[])
{
HANDLE hInRead;
HANDLE hInWrite;
HANDLE hOutRead;
HANDLE hOutWrite;
SECURITY_ATTRIBUTES sa;
memset(&sa, 0, sizeof(SECURITY_ATTRIBUTES));
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = true;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
if (!CreatePipe(&hInRead, &hInWrite, &sa, 0)) {
cout << "CreatePipe1 error!" << endl;
exit(-1);
}
if (!CreatePipe(&hOutRead, &hOutWrite, &sa, 0)) {
cout << "CreatePipe2 error!" << endl;
exit(-1);
}
STARTUPINFO startupInfo;
memset(&startupInfo, 0, sizeof(STARTUPINFO));
startupInfo.cb = sizeof(STARTUPINFO);
startupInfo.dwFlags |= STARTF_USESTDHANDLES;
startupInfo.hStdInput = hInRead;
startupInfo.hStdOutput = hOutWrite;
startupInfo.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
PROCESS_INFORMATION proInfo;
memset(&proInfo, 0, sizeof(PROCESS_INFORMATION));
if (!CreateProcess("../Debug/anonymous_pipe_child.exe", //子进程的路径
NULL,
NULL,
NULL,
true,
CREATE_NEW_CONSOLE,
NULL,
NULL,
&startupInfo,
&proInfo)) {
cout << "create process error!";
exit(-1);
}
::CloseHandle(proInfo.hThread);
::CloseHandle(proInfo.hProcess);
::CloseHandle(hInRead);
::CloseHandle(hOutWrite);
//写入数据到子进程
char str[50] = "hello child! (FORM father)";
DWORD NumberOfBytesWritten;
WriteFile(hInWrite, str, strlen(str), &NumberOfBytesWritten, NULL);
memset(str, 0, sizeof(str));
ReadFile(hOutRead, str, sizeof(str), &NumberOfBytesWritten, NULL);
str[NumberOfBytesWritten] = '