NamedPipe

#include<iostream>
#include<windows.h>
#include<ctime>
using namespace std;
DWORD WINAPI thread1(LPVOID param)
{
char buf[256];
DWORD rlen=0;
HANDLE hPipe = CreateNamedPipe(TEXT("\\\\.\\Pipe\\mypipe"),PIPE_ACCESS_DUPLEX,PIPE_TYPE_MESSAGE|PIPE_READMODE_MESSAGE|PIPE_WAIT
,PIPE_UNLIMITED_INSTANCES,0,0,NMPWAIT_WAIT_FOREVER,0);//创建了一个命名管道
if(ConnectNamedPipe(hPipe, NULL)==NULL)//等待另一客户的链接。
{
cerr<<"链接失败!"<<endl;
}
else
{
cerr<<"链接成功"<<endl;
}
l:
if(ReadFile(hPipe,buf,256,&rlen,NULL)==FALSE)//读取管道中的内容(管道是一种特殊的文件)
{
CloseHandle(hPipe);//关闭管道
cerr<<"read data from Pipe failed!"<<endl;
}
else
{
cout<<"thread1 get data="<<buf<<" size="<<rlen<<endl;
char wbuf[256]="hahaha";
sprintf(wbuf,"%s   %d",wbuf,rand()%1000);
DWORD wlen=0;
WriteFile(hPipe,wbuf,sizeof(wbuf),&wlen,0);
cout<<"thread1 write data to pipe,data="<<wbuf<<" size="<<wlen<<endl;//收完发
_sleep(1000);
goto l;//如果接收成功,则继续接收。
}
return 0;
}
DWORD WINAPI thread2(LPVOID param)
{
char buf[256]="lauo pipe test...\0\0";
sprintf(buf,"%s   %d",buf,rand()%1000);
DWORD wlen=0;
Sleep(1000);//等待pipe的创建成功!
if (WaitNamedPipe(TEXT("\\\\.\\Pipe\\mypipe"), NMPWAIT_WAIT_FOREVER) == FALSE)
{
cerr<<"connect the namedPipe failed!"<<endl;
return 0;
}
HANDLE hPipe=CreateFile(TEXT("\\\\.\\Pipe\\mypipe"), GENERIC_READ | GENERIC_WRITE, 0,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if((long)hPipe==-1)
{
cerr<<"open the exit pipe failed!"<<endl;
return 0;
}
while(1)
{
if(WriteFile(hPipe,buf,sizeof(buf),&wlen,0)==FALSE)
{
cerr<<"write to pipe failed!"<<endl;
}
else
{
cout<<"write size="<<wlen<<endl;
char rbuf[256];
DWORD rlen=0;
ReadFile(hPipe,rbuf,sizeof(rbuf),&rlen,0);//这里可以测试,一发必先有一收(另一进程中),否则将无法继续(阻塞式)
cout<<"thread2 read from pipe data="<<rbuf<<" size="<<rlen<<endl<<endl;
}
_sleep(1000);
}
return 0;
}
int main()
{
srand((unsigned)time(NULL));
CreateThread(0,0,thread1,0,0,0);
CreateThread(0,0,thread2,0,0,0);
while(1) Sleep(1000);
return 1;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值