进程间通信——匿名管道

使用匿名管道做进程通信,需要用父进程创建一个子进程,该子进程的标准输入输出句柄由父进程指定。
无论父进程还是子进程,都可以收发数据,这里仅演示父进程发数据,子进程打印数据。
父进程循环从控制台读数据,并发送给子进程,子进程用对话框打印数据,约定子进程收到"quit"后退出。
父进程(发送端)

#define _CRT_SECURE_NO_WARNINGS #include #include HANDLE g_hRead, g_hWrite; BOOL CreateChildProcess() { // 创建可继承的匿名管道,可以理解成输入输出设备 SECURITY_ATTRIBUTES sa; sa.bInheritHandle = TRUE; sa.lpSecurityDescriptor = NULL; sa.nLength = sizeof(SECURITY_ATTRIBUTES); if (!CreatePipe(&g_hRead, &g_hWrite, &sa, 0)) { printf("创建匿名管道失败\n"); return FALSE; } // 创建子进程,设置标准输入输出设备 STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(STARTUPINFO)); si.cb = sizeof(STARTUPINFO); si.dwFlags = STARTF_USESTDHANDLES; si.hStdInput = g_hRead; si.hStdOutput = g_hWrite; si.hStdError = GetStdHandle(STD_ERROR_HANDLE); if (FALSE == CreateProcess(TEXT("C:\\Users\\gsy\\source\\repos\\2020年暑假学习\\Debug\\匿名管道-接收端.exe"), NULL, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) { //printf("创建进程失败\n"); CloseHandle(g_hRead); CloseHandle(g_hWrite); g_hRead = g_hWrite = NULL; return FALSE; } else { CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } return TRUE; }void SendData() { char szBuffer[0x100]; scanf("%s", szBuffer); DWORD dwWrite = 0; if (!WriteFile(g_hWrite, szBuffer, strlen(szBuffer) + 1, &dwWrite, NULL)) { printf("写数据失败\n"); } }int main() { if (CreateChildProcess()) { printf("创建子进程成功,输入要发送的数据,输入quit杀死子进程\n"); } else { printf("创建子进程失败\n"); } while (true) { SendData(); } return 0; }

子进程(接收端)
#include #include int main() { HANDLE hRead = GetStdHandle(STD_INPUT_HANDLE); HANDLE hWrite = GetStdHandle(STD_OUTPUT_HANDLE); char szBuffer[0x100]; DWORD dwRead = 0; while (true) { ReadFile(hRead, szBuffer, 0x100, &dwRead, NULL); if (strcmp(szBuffer, "quit") == 0) { printf("quit!\n"); break; } printf("%s\n", szBuffer); MessageBoxA(0, szBuffer, "子进程接收到的数据", MB_OK); } return 0; }

运行结果(运行父进程程序) 【进程间通信——匿名管道】进程间通信——匿名管道
文章图片

    推荐阅读