预览
正文
环境:
基于单文档的应用程序
第一步:
我们先在我们的MENU中创建响应的菜单项(创建管道、读取数据、写入数据)
第二步:
对这三个菜单项进行建立响应函数——这里我们先来定义两个管道的读写句柄,注意要在我们的View中的构造函数中进行初始化
第三步:
我们在我们的View中的析构函数中对这两个句柄进行判断,如果还有的话,我们要将他们释放,以回收内存。
第四步:
我们来创建一个匿名管道
SECURITY_ATTRIBUTES sa;
sa.bInheritHandle=true;
sa.lpSecurityDescriptor=NULL;
sa.lpSecurityDescriptor=sizeof(SECURITY_ATTRIBUTES);
if (!CreatePipe(&hread,&hwrite,&sa,0))
{
MessageBox("创建匿名管道失败!");
return;
}
第五步:
启动子进程,传递管道以及创建管道
void CParentView::OnPipeCreate()
{
// TODO: Add your command handler code here
SECURITY_ATTRIBUTES sa;
sa.bInheritHandle=true;
sa.lpSecurityDescriptor=NULL;
sa.lpSecurityDescriptor=sizeof(SECURITY_ATTRIBUTES);
if (!CreatePipe(&hread,&hwrite,&sa,0))
{
MessageBox("创建匿名管道失败!");
return;
}
STARTUPINFO sui;
PROCESS_INFORMATION pi;
ZeroMemory(&sui,sizeof(STARTUPINFO));
sui.cb=sizeof(STARTUPINFO);
sui.dwFlags=STARTF_USESTDHANDLES;
sui.hStdInput=hread;
sui.hStdOutput=hwrite;
sui.hStdError=GetStdHandle(STD_ERROR_HANDLE);
if(!CreateProcess("..\\Child\\Debug\\Child.exe",NULL,NULL,NULL,true,0,NULL,NULL,&sui,&pi))
{
CloseHandle(hread);
CloseHandle(hweite);
hread=NULL;
hwrite=NULL;
MessageBox("创建子进程失败!");
return;
}
else
{
CloseHandle(pi.hProcess);//关闭子进程的句柄
CloseHandle(pi.hThread);//关闭返回的主线程的句柄
}
}
第六步:
管道的读取和写入
oid CParentView::OnPipeRead()
{
// TODO: Add your command handler code here
char buf[100];
DWORD dwread;
if(!ReadFile(hread,buf,100,&dwread,NULL))
{
MessageBox("读取数据失败!");
return;
}
MessageBox(buf);
}
void CParentView::OnPipeWrite()
{
// TODO: Add your command handler code here
char buf[]="wangjilibrian";
DWORD dwwrite;
if (!WriteFile(hwrite,buf,strlen(buf)+1,&dwwrite,NULL))
{
MessageBox("写入数据失败!");
return;
}
}