匿名管道在父子进程间通讯:
子进程及管道创建:
string strFilePath = GetExName();
strFilePath = ExtractFilePath(strFilePath);
strFilePath = strFilePath +"DTUse.exe";
STARTUPINFO sinf = {0};
PROCESS_INFORMATION pinf = {0};
SECURITY_ATTRIBUTES sa = {0};
sa.nLength = sizeof(sa);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;
CreatePipe(&hPipeRead, &hPipeWrite, &sa, 0);
sinf.cb = sizeof(sinf);
sinf.dwFlags = STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES;
sinf.wShowWindow = SW_HIDE;
sinf.hStdInput = hPipeRead;
sinf.hStdOutput = hPipeWrite;
sinf.hStdError = GetStdHandle(STD_ERROR_HANDLE);;
if (!CreateProcess(NULL, (LPSTR)strFilePath.c_str(), NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS, NULL, NULL, &sinf, &pinf))
{
MessageBox("Create Process Error!");
return 0;
}
CloseHandle(pinf.hThread);
CloseHandle(pinf.hProcess);
HANDLE hThread1 = (HANDLE)_beginthreadex(NULL, 0,pipe_read_func , (void*)this, 0, NULL);
if (hThread1 != NULL)
{
CloseHandle(hThead1);
}
读取线程:
static unsigned int __stdcall pipe_read_func(void* arg)
{
DWORD iLen = 0;
char cBuf[1024] = {0};
while(1){
if(ReadFile(hPipeRead, cBuf, 1024,&iLen,NULL))
{
log_msg(":%s \n",cBuf);
//在此处理子进程发过来的数据。
}
else
{
log_msg(":client close \n");
break;
}
}
CloseHandle(hPipeRead);
hPipeRead = NULL;
CloseHandle(hPipeWrite);
hPipeWrite = NULL;
return 0;
}
父进程发送处理:
bool blRet = WriteFile(hPipeWrite, strctSendMessage.pBuf, strlen(strctSendMessage.pBuf),&iLen,NULL);
blRet = WriteFile(hPipeWrite, " ", 1,&iLen,NULL);//跟发一个空串,否则子进程可能不能及时收到前面发的有效内容 20190509
log_msg("\nWRITE NUM = %d ret=%d %s\n",blRet, iLen,strctSendMessage.pBuf);
子进程获取管道句柄:
hPipeRead = GetStdHandle(STD_INPUT_HANDLE);
hPipeWrite = GetStdHandle(STD_OUTPUT_HANDLE);
HANDLE hThread1 = (HANDLE)_beginthreadex(NULL, 0, pipe_read_func, (void*)this, 0, NULL);
if (hThread1 != NULL){
CloseHandle(hThread1);
}
读取线程
static unsigned int __stdcall pipe_read_func(void* arg)
{
DWORD iLen = 0;
char cBuf[1024] = { 0 };
while (!pThis->m_blExitInstance) {
if (ReadFile(hPipeRead, cBuf, 1024, &iLen, NULL)){
log_msg("readpipe len=%d,info=%s \n",iLen, cBuf);
//这儿是收到父进程命令后的处理。
if (strstr(cBuf, "{") != NULL && strstr(cBuf, "}") != NULL) {
string strMsg = Utf8ToAscii(cBuf);
m_csLock.Lock();
m_deqCmdInfo.push_back(strMsg);
m_csLock.Unlock();
}
}else{
log_msg("ReadFile error \n");
break;
}
}
CloseHandle(hPipeRead);
hPipeRead = NULL;
return 0;
}