代码如下,这样是没有问题的,子进程收到hello child之后会返回信息。只是不知为什么 区域A 中的 问题代码 必须要在创建进程之前 关闭写句柄? 如果放到 CreateProcess之后 ,ReadFile就会一直卡在那,子进程估计没有返回,但这是为什么? 这个程序目前遇到的问题是区域A的信息成功写进去了,随后的句柄被关闭了,等子进程创建完毕后,再用区域B的WriteFile肯定是没办法写进去了,而区域C的ReadFile能读出来,但这样的话,我要是想在CreateProcess之后使用WriteFile怎么办呢?请各位指点指点!谢谢!
#include <windows.h>
#include <stdio.h>
#include "string.h"
int main(){
char* path="./Debug/child.exe";
HANDLE hChildRead,hFatherWrite,hChildWrite,hFatherRead;
SECURITY_ATTRIBUTES safe={0};
char szSendBuffer[256],szRecieveBuffer[256],*p=szRecieveBuffer;
strcpy(szSendBuffer,"hello child");
DWORD dwLen;
safe.bInheritHandle=TRUE;
safe.lpSecurityDescriptor=NULL;
safe.nLength=sizeof(SECURITY_ATTRIBUTES);
CreatePipe(&hChildRead,&hFatherWrite,&safe,0); //子进程1读管道
CreatePipe(&hFatherRead,&hChildWrite,&safe,0); //子进程1写管道
//**********************************A区域*****************************************
if(!WriteFile(hFatherWrite,szSendBuffer,strlen(szSendBuffer)+1,&dwLen,NULL))
{
puts("写管道失败!");
exit(0);
}
puts("写管道成功!");
CloseHandle(hFatherWrite); //问题代码
//***********************************************************************************
STARTUPINFO info={0};
PROCESS_INFORMATION pro;
GetStartupInfo(&info);
info.cb=sizeof(STARTUPINFO);
info.dwFlags=STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES;
info.wShowWindow=SW_HIDE;
info.hStdInput=hChildRead;
info.hStdOutput=hChildWrite;
info.hStdError=hChildWrite;
if(!CreateProcess(path,NULL,NULL,NULL,TRUE,NULL,NULL,NULL,&info,&pro))
{
puts("创建子进程失败!");
exit(0);
}
CloseHandle(hFatherWrite);
puts("进程创建成功!");
CloseHandle(pro.hProcess);
CloseHandle(pro.hThread);
//************************************B区域******************************************
if(!WriteFile(hFatherWrite,szSendBuffer,strlen(szSendBuffer)+1,&dwLen,NULL))
{
puts("写管道失败!");
//exit(0);
}
else
puts("写管道成功!");
//***********************************************************************************
//************************************C区域******************************************
//CloseHandle(hFatherWrite);
if(!ReadFile(hFatherRead,szRecieveBuffer,256,&dwLen,NULL))
{
puts("读管道失败!");
exit(0);
}
*(p+dwLen)='\0';
printf("%s\n",szRecieveBuffer);
//***********************************************************************************
CloseHandle(hChildRead);
CloseHandle(hChildWrite);
CloseHandle(hFatherRead);
return 0;
}