服务端: int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { printf("==============NamedPipe服务端==============/r/n"); //创建管道MyPipe HANDLE hPipe = CreateNamedPipe( _T(".//pipe//MyPipe"), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0, 1, 1024, 1024, 0 , NULL); if (INVALID_HANDLE_VALUE == hPipe) { printf("CreateNamedPipe is failed!/r/n"); return -1; } HANDLE hEvent; hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); OVERLAPPED ovlap; ZeroMemory(&ovlap, sizeof(ovlap)); ovlap.hEvent = hEvent; //ConnectNamedPipe相当于Accept ConnectNamedPipe(hPipe, &ovlap); //一直等到有客户端的连接 WaitForSingleObject(hEvent, INFINITE); CloseHandle(hEvent); int args[2]; DWORD dwRead, dwWrite; //读取 ReadFile(hPipe, args, sizeof(args), &dwRead, NULL); int a = args[0]; int b = args[1]; printf("NamedPipe服务端读取到参数(%d, %d)/r/n", a, b); int c = Plus(a,b); //写入 WriteFile(hPipe, &c, sizeof(c), &dwWrite, NULL); printf("NamedPipe服务端计算出结果%d + %d = %d已经写入命名管道/r/n", a, b, c); printf("按任意键关闭程序.../r/n"); _getch(); return 0; } 客户端: int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { printf("==============NamedPipe客户端==============/r/n"); //WaitNamedPipe相当于Connect if (!WaitNamedPipe(_T(".//pipe//MyPipe"), NMPWAIT_WAIT_FOREVER)) { printf("Not Found MyPile! Start up your NamedPipeServer../r/n"); return -1; } HANDLE hPipe = CreateFile(_T(".//pipe//MyPipe"), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE == hPipe) { printf("CreateNamedPipeCilent is failed!/r/n"); return -1; } DWORD dwWrite = 0; int args[] = {16, 26}; WriteFile(hPipe, args, sizeof(args), &dwWrite, NULL); printf("参数(%d, %d)已经写入,按任意键读取结果.../r/n", args[0], args[1]); _getch(); int c = -1; DWORD dwRead; ReadFile(hPipe, &c, sizeof(c), &dwWrite, NULL); printf("客户端读取到计算结果:%d + %d = %d/r/n", args[0], args[1], c); return 0; } 测试运行结果: ==============NamedPipe服务端============== NamedPipe服务端读取到参数(16, 26) NamedPipe服务端计算出结果16 + 26 = 42已经写入命名管道 按任意键关闭程序... ==============NamedPipe客户端============== 参数(16, 26)已经写入,按任意键读取结果... 客户端读取到计算结果:16 + 26 = 42 请按任意键继续. . .