15,471
社区成员
发帖
与我相关
我的任务
分享
#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;
}
HANDLE hPipeRead = NULL;
HANDLE hPipeWrite = NULL;
SECURITY_ATTRIBUTES sa = {0};
sa.bInheritHandle=TRUE;
sa.lpSecurityDescriptor=NULL;
sa.nLength=sizeof(SECURITY_ATTRIBUTES);
if(!CreatePipe(&hPipeRead,&hPipeWrite,&sa,0))
{
MessageBox("创建匿名管道失败!"); //传进管道失败的话,返回值是0
return;
}
STARTUPINFO info = {0};
PROCESS_INFORMATION pro = {0};
GetStartupInfo(&info);
info.cb=sizeof(STARTUPINFO);
info.dwFlags=STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES;
info.wShowWindow=SW_HIDE;
info.hStdInput=hPipeRead; //将结构体的标准输入句柄设置为管道的读取句柄
info.hStdOutput=hPipeWrite; //将结构体的标准输出句柄设置为管道的写入句柄
info.hStdError=GetStdHandle(STD_ERROR_HANDLE);
if(!CreateProcess(path,NULL,NULL,NULL,TRUE,NULL,NULL,NULL,&info,&pro))
{
puts("创建子进程失败!");
exit(0);
}
在主程序退出之前closehandle hPipeRead、hPipeWrite