使用CreateNamedPipe进行 进程通信的示例

来源:互联网 发布:董洁王大治知乎 编辑:程序博客网 时间:2024/05/02 08:43

使用CreateNamedPipe进行 进程通信的示例。

#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;
}

原创粉丝点击