正文
下面我们来利用命名管道来创建我们进程间的通信:
第一步:
我们来建立一个MFC的基于的单文档的应用程序
第二步:
我们在我们的资源里面的菜单中建立我们需要的菜单项,并对其建立命令消息响应
第三步:
我们来建立一个成员变量用来存放我们的句柄,并在构造函数中对其进行初始化,在析构函数中将其释放
CNamedpipeView::CNamedpipeView()
{
// TODO: add construction code here
hpipe=NULL;
}
CNamedpipeView::~CNamedpipeView()
{
if (hpipe)
{
CloseHandle(hpipe);
}
}
第四步:我们来创建管道
void CNamedpipeView::OnPipeCreate()
{
// TODO: Add your command handler code here
hpipe=CreateNamedPipe("\\\\.\\pipe\\mypipe",PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,0,1,1024,1024,0,NULL);//创建一个命名管道
if (INVALID_HANDLE_VALUE==hpipe)
{
MessageBox("创建命名管道失败!");
hpipe=NULL;
return;
}
//去等待客户端连接请求的到来
HANDLE hevent;
hevent=CreateEvent(NULL,true,false,NULL);
if (!hevent)
{
MessageBox("创建事件对象失败!");
CloseHandle(hpipe);
hpipe=NULL;
return;
}
OVERLAPPED ovlap;
ZeroMemory(&ovlap,sizeof(OVERLAPPED));
ovlap.hEvent=hevent;
if (!ConnectNamedPipe(hpipe,&ovlap))
{
if (ERROR_IO_PENDING!=GetLastError())
{
MessageBox("等待客户端连接失败!");
CloseHandle(hpipe);
CloseHandle(hevent);
hpipe=NULL;
return;
}
}
if(WAIT_FAILED==WaitForSingleObject(hevent,INFINITE))
{
MessageBox("等待对象失败!");
CloseHandle(hpipe);
CloseHandle(hevent);
hpipe=NULL;
return;
}
CloseHandle(hevent);
}
第五步:我们来编写写入数据的代码
void CNamedpipeView::OnPipeRead()
{
// TODO: Add your command handler code here
char buf[100];
DWORD dwread;
if(!ReadFile(hpipe,buf,100,&dwread,NULL))
{
MessageBox("读取数据失败!");
return;
}
MessageBox(buf);
}
第六步:我们拉编写读取数据的代码
void CNamedpipeView::OnPipeWrite()
{
// TODO: Add your command handler code here
char buf[]="990561853";
DWORD dwwrite;
if (!WriteFile(hpipe,buf,strlen(buf)+1,&dwwrite,NULL))
{
MessageBox("写入数据失败!");
return;
}
}