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

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

#include
#include
#include
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<<"链接失败!"< }
else
{
   cerr<<"链接成功"< }
l:
if(ReadFile(hPipe,buf,256,&rlen,NULL)==FALSE)//读取管道中的内容(管道是一种特殊的文件)
{
   CloseHandle(hPipe);//关闭管道
   cerr<<"read data from Pipe failed!"< }
else
{
   cout<<"thread1 get data="<    sprintf(wbuf,"%s   %d",wbuf,rand()%1000);
   DWORD wlen=0;
   WriteFile(hPipe,wbuf,sizeof(wbuf),&wlen,0);
   cout<<"thread1 write data to pipe,data="< 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!"<    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!"<    return 0;
}
while(1)
{
   if(WriteFile(hPipe,buf,sizeof(buf),&wlen,0)==FALSE)
   {
    cerr<<"write to pipe failed!"<    }
   else
   {
    cout<<"write size="<     char rbuf[256];
    DWORD rlen=0;
    ReadFile(hPipe,rbuf,sizeof(rbuf),&rlen,0);//这里可以测试,一发必先有一收(另一进程中),否则将无法继续(阻塞式)
    cout<<"thread2 read from pipe data="<

你可能感兴趣的:(使用CreateNamedPipe进行 进程通信的示例)