最近有一项工作要用到命名管道,发现有些地方不太清楚,所以重新理了一遍,写了个例子。
#include<iostream>
#include<windows.h>
#include<ctime>
#include <string>
using namespace std;
#define PIPENAME L"\\\\.\\Pipe\\mypipe"
#define MAX_WAIT_TIME 10
string ReadPipe(HANDLE hPipe);
BOOL WritePipe(HANDLE hPipe, const string & msg);
DWORD WINAPI thread1(LPVOID param);
DWORD WINAPI thread2(LPVOID param);
int main()
{
setlocale(LC_ALL, "CHS"); // 设置环境语言
HANDLE h1, h2;
h1 = CreateThread(0,0,thread1,0,0,0);
h2 = CreateThread(0,0,thread2,0,0,0);
WaitForSingleObject(h1, INFINITE);
return 1;
}
DWORD WINAPI thread1(LPVOID param)
{
string rMsg;
string wMsg;
char buf[256];
DWORD rlen=0;
int iCount=0;
HANDLE hPipe = CreateNamedPipe(PIPENAME,
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_MESSAGE|PIPE_READMODE_MESSAGE|PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES,
0,
0,
NMPWAIT_WAIT_FOREVER,
0); //创建了一个命名管道
if(ConnectNamedPipe(hPipe, NULL)) //等待另一客户的链接,可以不用
{
cout<<"thread1 连接管道成功"<<endl;
}
else
{
cout<<"thread1 连接管道失败!"<<endl;
}
while(true)
{
rMsg = ReadPipe(hPipe);
if (!rMsg.empty())
{
printf("thread1 第 %d 次 读取到的内容 = %s\n", iCount, rMsg.c_str());
printf("\n");
}
else
{
printf("thread1 第 %d 次 读取失败\n", iCount);
}
sprintf(buf, "111 time = %I64d icount = %d", time(0), iCount);
wMsg = buf;
if (WritePipe(hPipe, wMsg))
{
printf("thread1 第 %d 次 写入成功\n", iCount);
}
else
{
printf("thread1 第 %d 次 写入失败\n", iCount);
}
iCount++;
}
return 0;
}
DWORD WINAPI thread2(LPVOID param)
{
char buf[256];
DWORD wlen=0;
int icount = 0;
string rMsg;
string wMsg;
Sleep(1000);
if (WaitNamedPipe(PIPENAME, NMPWAIT_WAIT_FOREVER))
{
printf("thread2 命名管道存在 开始读写\n");
}
HANDLE hPipe=CreateFile(PIPENAME, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); // 连接命名管道
if((long)hPipe==-1)
{
printf("thread2 打开存在的管道失败!\n");
return 0;
}
int i=0;
while(1)
{
sprintf(buf, "222 time = %I64d icount = %d", time(0), icount);
wMsg = buf;
if (WritePipe(hPipe, wMsg))
{
printf("thread2 第 %d 次 写入成功\n", icount);
}
else
{
printf("thread2 第 %d 次 写入失败\n", icount);
}
rMsg = ReadPipe(hPipe);
if (!rMsg.empty())
{
printf("thread2 第 %d 次 读取到的内容 = %s\n", icount, rMsg.c_str());
printf("\n");
}
else
{
printf("thread2 第 %d 次 读取失败\n", icount);
}
icount++;
}
CloseHandle(hPipe);
return 0;
}
string ReadPipe(HANDLE hPipe)
{
int iCount;
DWORD pipSizeL, pipSizeH;
DWORD readLen;
string msg;
char *buf;
pipSizeL = 0;
iCount = 0;
if (hPipe == NULL)
{
return msg;
}
while(pipSizeL == 0)
{
if (iCount >= 10)
{
break;
}
pipSizeL = GetFileSize(hPipe, &pipSizeH);
iCount++;
Sleep(1000);
}
if (pipSizeL == 0)
{
return msg;
}
buf = new char[pipSizeL+1];
memset(buf, 0, pipSizeL+1);
if(ReadFile(hPipe, buf, pipSizeL, &readLen, NULL)) //读取管道中的内容(管道是一种特殊的文件)
{
if (pipSizeL == readLen)
{
msg = buf;
}
}
delete [] buf;
buf = NULL;
return msg;
}
BOOL WritePipe(HANDLE hPipe, const string & msg)
{
DWORD wlen;
return WriteFile(hPipe, msg.c_str(), msg.length(), &wlen, NULL);
}