命名管道-简单的例子
#include "stdafx.h" #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; } while (true) { 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]="server message!!!"; 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(5000); } } return 0; } DWORD WINAPI thread2(LPVOID param) { char buf[256]="client message!!!"; 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(5000); } return 0; } int main() { srand((unsigned)time(NULL)); CreateThread(0,0,thread1,0,0,0); CreateThread(0,0,thread2,0,0,0); system("pause"); return 1; }