进程间通信(匿名管道)

/ win32+MFC / 没有评论 / 431浏览

###父进程

#include <iostream>
#include <windows.h>
#include <atlstr.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(L"test.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] = '\0';

	//弹出获得的数据
	USES_CONVERSION;
	LPCWSTR str2;
	str2 = A2W(str);
	MessageBox(::GetConsoleWindow(), str2, L"anonymous_pipe", MB_OK);
	::CloseHandle(hOutRead);
	::CloseHandle(hInWrite);
	return 0;
}

###子进程

#include <iostream>
#include <windows.h>
#include <atlstr.h>
using namespace std;

int main(int argc, char *argv[])
{
	//获得标准输入输出句柄
	HANDLE hRead = ::GetStdHandle(STD_INPUT_HANDLE);
	HANDLE hWrite = ::GetStdHandle(STD_OUTPUT_HANDLE);

	char str[50];
	DWORD  NumberOfBytesWritten;
	
	//获取父进程写进的数据,并且弹出
	memset(str, 0, sizeof(str));
	ReadFile(hRead, str, sizeof(str), &NumberOfBytesWritten, NULL);
	str[NumberOfBytesWritten] = '\0';

	USES_CONVERSION;
	LPCWSTR str2;
	str2 = A2W(str);
	MessageBox(::GetConsoleWindow(), str2, L"anonymous_pipe_child", MB_OK);

	//子进程重新写入数据
	strcpy_s(str, "hello father! (FORM child)");
	WriteFile(hWrite, str, strlen(str), &NumberOfBytesWritten, NULL);

	::CloseHandle(hRead);
	::CloseHandle(hWrite);

	return 0;
}