管道PIPE跨进程通讯
2023-11-24
7
0
发送端
#define EXAMP_PIPE L"\\\\.\\PIPE\\EB3F2E4B_52E2_40F9_A17D_B4A2588F23AB"
#define BUF_SIZE 4096
void CPipeDlg::SendData(PUCHAR pData, ULONG nLen)
{
HANDLE hPipe = NULL;
hPipe = CreateFile(EXAMP_PIPE, GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, 0, NULL);
if (hPipe == INVALID_HANDLE_VALUE)
{
return ;
}
//if (!WaitNamedPipe(EXAMP_PIPE, NMPWAIT_USE_DEFAULT_WAIT))
//{
// CloseHandle(hPipe);
// return;
//}
DWORD dwReturn = 0;
if (!WriteFile(hPipe, pData, nLen, &dwReturn, NULL))
{
}
CloseHandle(hPipe);
}
接收端:
#define BUF_SIZE 4096
// 定义管道名 , 如果是跨网络通信 , 则在圆点处指定服务器端程序所在的主机名
#define EXAMP_PIPE L"\\\\.\\PIPE\\EB3F2E4B_52E2_40F9_A17D_B4A2588F23AB"
void CShowDlg::PipeDebug()
{
while(1)
{
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 ;
}
if (!ConnectNamedPipe(hPipe, NULL))
{
return;
}
DWORD dwReturn = 0;
char szBuffer[BUF_SIZE] = { 0 };
memset(szBuffer, 0, BUF_SIZE);
if (ReadFile(hPipe, szBuffer, BUF_SIZE, &dwReturn, NULL))
{
ZCAN_Receive_Data* rcv =(ZCAN_Receive_Data*)szBuffer;
ProcessCanMsg(*rcv);
}
CloseHandle(hPipe);
}
}