服务器端:
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { printf("==========这里是服务器端==========/r/n"); //获取标准输入、输出句柄 HANDLE hStdIn = ::GetStdHandle(STD_INPUT_HANDLE); HANDLE hStdOut = ::GetStdHandle(STD_OUTPUT_HANDLE); DWORD dwRead = 0; //从标准输入中读取参数 int args[2]; ReadFile(hStdIn, args, sizeof(args), &dwRead, NULL); if(dwRead > 0) { //加法计算 int a = args[0]; int b = args[1]; int c = Plus(a,b); DWORD dwWrite = 0; WriteFile(hStdOut, &c, sizeof(c), &dwWrite, NULL); } return 0; }
客户端:
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { printf("==========这里是客户端==========/r/n"); HANDLE hChildStdInRead, hChildStdInWrite; HANDLE hChildStdOutRead, hChildStdOutWrite; //安全属性 SECURITY_ATTRIBUTES sa; sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.bInheritHandle = TRUE; //子进程可以继承父进程创建管道的读写句柄 sa.lpSecurityDescriptor = NULL; //创建标准输入管道 if (!CreatePipe(&hChildStdInRead, &hChildStdInWrite, &sa, 0)) { printf("Create inPipe failed!/r/n"); return -1; } //创建标准输出管道 if (!CreatePipe(&hChildStdOutRead, &hChildStdOutWrite, &sa, 0)) { printf("Create outPipe failed!/r/n"); return -1; } //进程属性 PROCESS_INFORMATION pi; STARTUPINFO si = { sizeof(si) }; si.wShowWindow = SW_HIDE; si.hStdInput = hChildStdInRead; si.hStdOutput = hChildStdOutWrite; si.hStdError = GetStdHandle(STD_ERROR_HANDLE); si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; //使用显示窗口和标准句柄的标志 TCHAR cCommandLine[_MAX_PATH] = _T("PipeServer.exe"); //启动PipeServer.exe if (CreateProcess(NULL, cCommandLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, π)) { CloseHandle(pi.hProcess); CloseHandle(pi.hThread); DWORD dwWrite = 0; int args[] = {16, 26}; //发送参数值 WriteFile(hChildStdInWrite, args, sizeof(args), &dwWrite, NULL); printf("客户端正写入管道的参数:(%d, %d)/r/n", args[0], args[1]); DWORD dwRead = 0; int c = 0; ReadFile(hChildStdOutRead, &c, sizeof(c), &dwRead, NULL); printf("客户端读取管道的计算结果:%d + %d = %d/r/n", args[0], args[1], c); } return 0; }
测试结果:
==========这里是服务器端========== ==========这里是客户端========== 客户端正写入管道的参数:(16, 26) 客户端读取管道的计算结果:16 + 26 = 42 请按任意键继续. . .