本文章是介绍在Windows下,使用PIPE管道实现进程间通讯,可是实现两个进程之前相互发送读取消息。
主进程代码
usingnamespacestd; // 定义管道名 , 如果是跨网络通信 , 则在圆点处指定服务器端程序所在的主机名intmain(intargc, TCHAR*argv[], TCHAR*envp[]) { // 创建命名管道HANDLEhPipe=NULL; hPipe=CreateNamedPipe( EXAMP_PIPE, PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE|PIPE_READMODE_MESSAGE|PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, BUF_SIZE, BUF_SIZE, 0, NULL); if (hPipe==INVALID_HANDLE_VALUE) { cout<<"Create Read Pipe Error"<<endl; returnFALSE; } cout<<"Wait for the connection"<<endl; // 等待客户端的连接if (!ConnectNamedPipe(hPipe, NULL)) { cout<<"Connect Failed"<<endl; returnFALSE; } DWORDdwReturn=0; charszBuffer[BUF_SIZE] = { 0 }; // 向客户端发送数据cout<<"Wait for input"<<endl; cin>>szBuffer; if (!WriteFile(hPipe, szBuffer, strlen(szBuffer), &dwReturn, NULL)) { cout<<"Write Failed"<<endl; } // 读取客户端数据memset(szBuffer, 0, BUF_SIZE); if (ReadFile(hPipe, szBuffer, BUF_SIZE, &dwReturn, NULL)) { szBuffer[dwReturn] ='\0'; cout<<szBuffer<<endl; } else { cout<<"Read Failed"<<endl; } DisconnectNamedPipe(hPipe); CloseHandle(hPipe); return0; }
子进程代码
usingnamespacestd; // 定义管道名 , 如果是跨网络通信 , 则在圆点处指定服务器端程序所在的主机名intmain(intargc, TCHAR*argv[], TCHAR*envp[]) { HANDLEhPipe=NULL; charszBuffer[BUF_SIZE] = { 0 }; DWORDdwReturn=0; // 判断是否有可以利用的命名管道 if (!WaitNamedPipe(EXAMP_PIPE, NMPWAIT_USE_DEFAULT_WAIT)) { cout<<"No Read Pipe Accessible"<<endl; return0; } // 打开可用的命名管道 , 并与服务器端进程进行通信 hPipe=CreateFile(EXAMP_PIPE, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); if (hPipe==INVALID_HANDLE_VALUE) { cout<<"Open Read Pipe Error"<<endl; return0; } cout<<"Wait for the message"<<endl; // 读取服务端发来的数据if (ReadFile(hPipe, szBuffer, BUF_SIZE, &dwReturn, NULL)) { szBuffer[dwReturn] ='\0'; cout<<szBuffer<<endl; } else { cout<<"Read Failed"<<endl; } // 向服务端发送数据memset(szBuffer, 0, BUF_SIZE); cin>>szBuffer; if (!WriteFile(hPipe, szBuffer, strlen(szBuffer), &dwReturn, NULL)) { cout<<"Write Failed"<<endl; } CloseHandle(hPipe); return0; }