进程间通信——命名管道

服务端

// 规定创建命名管道的程序是服务端 // 本程序服务端负责接收数据并打印 #include #include BOOL Server() { char szBuffer[0x100] = { 0 }; DWORD dwRead = 0; // 创建双向管道 HANDLE hPipe = CreateNamedPipeA("\\\\.\\pipe\\hambaga", PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, 1, 0, 0, 1000, NULL); if (INVALID_HANDLE_VALUE =https://www.it610.com/article/= hPipe) { printf("创建命名管道失败\n"); CloseHandle(hPipe); return -1; } printf("创建命名管道成功,等待客户端连接...\n"); if (ConnectNamedPipe(hPipe, NULL) == FALSE) { printf("与客户机连接失败\n"); CloseHandle(hPipe); return -1; } while (1) { printf("正在等待数据: "); if (ReadFile(hPipe, szBuffer, 0x100, &dwRead, NULL) == FALSE) { printf("读取数据失败\n"); break; }szBuffer[dwRead] = 0; printf("%s\n", szBuffer); } CloseHandle(hPipe); return TRUE; }int main() { Server(); return 0; }

客户端
#define _CRT_SECURE_NO_WARNINGS #include #include BOOL Client() { char szBuffer[0x100] = { 0 }; DWORD dwWrite = 0; if (WaitNamedPipeA("\\\\.\\pipe\\hambaga", NMPWAIT_WAIT_FOREVER) == FALSE) { printf("等待命名管道实例失败\n"); return FALSE; } HANDLE hPipe = CreateFileA("\\\\.\\pipe\\hambaga", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hPipe == INVALID_HANDLE_VALUE) { printf("创建命名管道失败\n"); CloseHandle(hPipe); return FALSE; } printf("连接服务器成功\n"); while (1) { scanf("%s", szBuffer); if (FALSE == WriteFile(hPipe, szBuffer, strlen(szBuffer), &dwWrite, NULL)) { printf("写入管道失败\n"); break; } } CloseHandle(hPipe); return TRUE; }int main() { Client(); system("pause"); return 0; }

运行结果 【进程间通信——命名管道】进程间通信——命名管道
文章图片

    推荐阅读