windows下命名管道、邮件槽使用学习

来源:互联网 发布:卡西欧750知乎 编辑:程序博客网 时间:2024/06/03 21:58

继续 进程间通讯的学习,命名管道

命名管道例子服务端
  • 创建管道 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 cbBytesRead;
char chRequest[BUFSIZE];
bool fSuccess = ReadFile (hPipe, chRequest, BUFSIZE, &cbBytesRead, NULL);
chRequest[cbBytesRead] = '\0';
printf("Data Received: %s\n",chRequest);
if (! fSuccess || cbBytesRead == 0) {
break;
}
DisconnectNamedPipe(hPipe);
} else {
CloseHandle(hPipe);
return -2;
}
}
CloseHandle(hPipe);
return 0;
}客户端
  • 直接使用 CreateFile 连接管道

    • 对消息类型也可以使用 CallNamedPipe

#include <windows.h>
#include <stdio.h>
#include <string.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;
char szPipeUpdate[200] = "Data from Named Pipe client";
WriteFile(hFile, szPipeUpdate, strlen(szPipeUpdate), &dwWrite, NULL);
printf("%i bytes has send", (int)dwWrite);
CloseHandle(hFile);
}
return 0;
}邮件槽
  • 调用 CreateMailslot

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

int main()
{
HANDLE hSlot = CreateMailslotW(L"\\\\.\\mailslot\\qt4\\dbzhang800", 0, MAILSLOT_WAIT_FOREVER, NULL);

if (hSlot == INVALID_HANDLE_VALUE) {
printf("CreateMailslot failed with %d\n", (int)GetLastError());
return -1;
} else {
printf("Mailslot created successfully.\n");
while (1) {
DWORD cbMsg = 0;
DWORD cMsg = 0;
if (GetMailslotInfo(hSlot, NULL, &cbMsg, &cMsg, NULL)) {
if (cbMsg == MAILSLOT_NO_MESSAGE) {
//printf("no message\n");
continue;
}
if (cMsg){
printf("has message\n");
char * buf = new char[cbMsg+1];
DWORD cbRead = 0;
ReadFile(hSlot, buf, cbMsg, &cbRead, NULL);
buf[cbMsg] = 0;
printf("------------\n%s %d\n-------------\n", buf, (int)cbRead);
delete [] buf;
}
}
}
}
return 0;
}
  • 客户端实现与前面命名管道一样,使用CreateFile

HANDLE hFile = CreateFileW(L"\\\\.\\mailslot\\qt4\\dbzhang800", GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);匿名管道
  • 用 CreatePipe 创建两个进程间的管道

参考
  • http://msdn.microsoft.com/en-us/library/aa365150%28VS.85%29.aspx

  • http://msdn.microsoft.com/en-us/library/aa365785%28v=VS.85%29.aspx

  • http://www.codersource.net/win32/named-pipes/createnamedpipe-creating-named-pipe-server.aspx

原创粉丝点击