/*
两个进程用命名管道实现售票,我思路是服务端先ReadFile,再WriteFile。客户端先WriteFile,再ReadFile。这样子两边都能共享同一个票数(tickets)。不知道为什么传了一次之后句柄就无效。
*/
// 这是客户端的代码
#include <windows.h>
#include <iostream>
using namespace std;
int main(void)
{
HANDLE hpip;
char buf[] = "命名管道测试程序";
DWORD readbuf;
DWORD writebuf;
int wait_time = 0;
int tickets = 100;
cout << "正在连接命名管道!" << endl;
if (WaitNamedPipe("\\\\.\\pipe\\pipename", NMPWAIT_WAIT_FOREVER)) //连接命名管道
{
hpip = CreateFile("\\\\.\\pipe\\pipename", GENERIC_READ | GENERIC_WRITE, 0, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
//打开指定命名管道
if (hpip == INVALID_HANDLE_VALUE)
{
cout << "打开命名管道失败!" << endl;
}
else
{
cout << "连接成功!" << endl;
while (1)
{
--tickets;
itoa(tickets, buf, 10);
if (WriteFile(hpip, buf, sizeof(buf), &writebuf, NULL))
{
cout << "writing..." << endl;
wait_time = rand() % 4901 + 100;
Sleep(wait_time);
cout << "窗口2售出一张票,剩余票数" << tickets << "等待时间" << wait_time << "毫秒" << endl;
}
else
{
cout << "DEBUG: " << tickets << endl;
cout << GetLastError() << endl;
Sleep(5000);
}
if (ReadFile(hpip, buf, 200, &readbuf, NULL))
{
cout << "reading..." << endl;
tickets = atoi(buf);
cout << "tickets: " << tickets << endl;
}
if (tickets == 0)
break;
}
}
}
else
{
cout << "连接命名管道失败!" << endl;
}
CloseHandle(hpip);
return 0;
}
// 这是服务端的代码
#include <windows.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(void)
{
HANDLE hpip;
OVERLAPPED ovi = {0};
char buf[200];
DWORD readbuf;
DWORD writebuf;
int tickets = 0;
int wait_time = 0;
hpip = CreateNamedPipe("\\\\.\\pipe\\pipename", PIPE_ACCESS_DUPLEX,
PIPE_TYPE_BYTE, 10, 0, 0, 0, NULL);
cout << "创建管道成功,正在等待客户连接!" << endl;
if (ConnectNamedPipe(hpip, &ovi))
{
cout << "客户端连接成功!" << endl;
cout << "正在读取数据!" << endl;
while (1)
{
if (ReadFile(hpip, buf, 200, &readbuf, NULL))
{
cout << "Reading..." << endl;
tickets = atoi(buf);
cout << "tickets: " << tickets << endl;
}
else
{
cout << "DEBUG: " << tickets << endl;
cout << GetLastError() << endl;
}
if (tickets == 0)
break;
tickets--;
itoa(tickets, buf, 10);
if (WriteFile(hpip, buf, sizeof(buf), &writebuf, NULL))
{
cout << "Writing..." << endl;
wait_time = rand() % 4901 + 100;
Sleep(wait_time);
cout << "窗口1售出一张票,剩余票数" << tickets << "等待时间" << wait_time << "毫秒" << endl;
}
else
{
cout << "DEBUG: " << tickets << endl;
cout << GetLastError() << endl;
}
}
}
CloseHandle(hpip);
return 0;
}