您的位置:首页 > 编程语言

进程间通信——管道代码实现

2011-09-05 10:01 190 查看
服务端

· 创建管道CreateNamedPipe
· 等待客户端连接ConnectNamedPipe
· Read 或 Write操作
· 断开连接DisconnectNamedPipe
· 关闭句柄

#include <windows.h>
#include <stdio.h>

const DWORD BUFSIZE = 1024;
const DWORD PIPE_TIMEOUT = 5000;

int main()
{
HANDLE hPipe = CreateNamedPipeW(
L"\\\\.\\pipe\\Dbzhang800Pipe",
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES,
BUFSIZE,
BUFSIZE,
PIPE_TIMEOUT,
NULL);

if (hPipe == INVALID_HANDLE_VALUE)
{
return -1;
}

for (;;)
{
if (ConnectNamedPipe(hPipe, NULL) || (GetLastError() == ERROR_PIPE_CONNECTED))
{
DWORD dwBytesRead = 0;
char szRequest[BUFSIZE];
BOOL bSuccess = ReadFile (hPipe, szRequest, BUFSIZE, &dwBytesRead, NULL);
szRequest[dwBytesRead] = '\0';
printf("Data Received: %s\n",szRequest);
if (! bSuccess || dwBytesRead == 0)		//读一个空字符串时退出
{
break;
}
DisconnectNamedPipe(hPipe);
}
else
{
CloseHandle(hPipe);
return -2;
}
}

CloseHandle(hPipe);
return 0;
}


客户端

· 直接使用CreateFile 连接管道
· 对消息类型也可以使用CallNamedPipe

#include <windows.h>
#include <stdio.h>

const DWORD BUFSIZE = 1024;
const DWORD PIPE_TIMEOUT = 5000;

int main()
{
HANDLE hFile = CreateFileW(
L"\\\\.\\pipe\\Dbzhang800Pipe",
GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
0,
NULL);

if(hFile == INVALID_HANDLE_VALUE)
{
printf("cannot connect to Named Pipe\n" );
}
else
{
DWORD dwWrite = 0;
char szPipeUpdate[200] = "Data from Named Pipe client";
WriteFile(hFile, szPipeUpdate, (DWORD)strlen(szPipeUpdate), &dwWrite, NULL);
printf("%i bytes has send", (int)dwWrite);
CloseHandle(hFile);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: