命名管道简单说明
是从网上各个帖子中学习的代码,因此代码的格式以及内容有粘贴网上其他大神的代码,如有侵权请告知删除
与共享内存作用一样,都是为了多进程对同一块信息进行读写操作
服务端:
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <ctime>
using namespace std;
int main()
{
//创建命名管道
HANDLE hPipe = CreateNamedPipe(L"\\\\.\\Pipe\\test",
PIPE_ACCESS_DUPLEX, //双向管道
PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, //消息形式写入|消息形式读出|同步操作在等待的时候挂起线程
1, //最大客户端数
0, //输出缓冲区长度,0代表默认
0, //输入缓冲区长度,0代表默认
NMPWAIT_WAIT_FOREVER, //一直阻塞
0);
if (hPipe == NULL)
{
DWORD dWErr = GetLastError();
cout << "The CreateNamedPipe ErrCode is " << dWErr << endl;
return -1;
}
cout << "Create Pipe Success" << endl;
//等待客户端连接
if (ConnectNamedPipe(hPipe, NULL) != NULL)
{
cout << "Connect Pipe Success" << endl;
DWORD dwWrite;
char *pStr = "This is Created by me[Server]";
if (!WriteFile(hPipe, pStr, strlen(pStr), &dwWrite, NULL))
{
cout << "Server Write Fail" << endl;
return -1;
}
cout << "Server Write String is: " << pStr << endl;
}
else
{
DWORD dWErr = GetLastError();
cout << "The ConnectNamedPipe ErrCode is " << dWErr << endl;
return -1;
}
DisconnectNamedPipe(hPipe);
CloseHandle(hPipe);
cout << "Close Pipe Success" << endl;
system("pause");
}
客户端:
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <ctime>
#include <conio.h>
using namespace std;
#define BUFSIZE 5
int main()
{
if (WaitNamedPipe(L"\\\\.\\Pipe\\test", NMPWAIT_WAIT_FOREVER) == FALSE)
{
cout << "Connect to Server Pipe Fail" << endl;
return -1;
}
HANDLE hPipe = CreateFile(L"\\\\.\\Pipe\\test",
GENERIC_READ | GENERIC_WRITE, //允许进行读访问|允许进行写访问
0,//表示不共享
NULL,
OPEN_EXISTING, //文件必须存在
FILE_ATTRIBUTE_NORMAL, //默认属性
NULL);
if (hPipe == NULL)
{
DWORD dWErr = GetLastError();
cout << "The CreateFile ErrCode is " << dWErr << endl;
return -1;
}
//获取服务端发送的消息
DWORD dwRead;
char Buffer[64] = { 0 };
string recvData = "";
while (true)
{
if (!ReadFile(hPipe, Buffer, 64, &dwRead, NULL))
{
cout << "ReadFile Error" << endl;
return -1;
}
cout << "Receive The Server Data:" << Buffer << endl;
}
FlushFileBuffers(hPipe);
DisconnectNamedPipe(hPipe);
CloseHandle(hPipe);
return 0;
}