匿名管道的使用及遇到问题的解决办法

匿名管道在父子进程间通讯:

 子进程及管道创建:

 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;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值