本文章是介绍在Windows下,使用PIPE管道实现进程间通讯,可是实现两个进程之前相互发送读取消息。
主进程代码
代码语言:javascript复制#include "windows.h"
#include <iostream>
using namespace std;
#define BUF_SIZE 4096
// 定义管道名 , 如果是跨网络通信 , 则在圆点处指定服务器端程序所在的主机名
#define EXAMP_PIPE L"\\.\PIPE\EB3F2E4B_52E2_40F9_A17D_B4A2588F23AB"
int main(int argc, TCHAR* argv[], TCHAR* envp[])
{
// 创建命名管道
HANDLE hPipe = 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;
return FALSE;
}
cout << "Wait for the connection" << endl;
// 等待客户端的连接
if (!ConnectNamedPipe(hPipe, NULL))
{
cout << "Connect Failed" << endl;
return FALSE;
}
DWORD dwReturn = 0;
char szBuffer[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] = '