关于使用ReadFile读管道时,函数一直阻塞的问题

在写Online Judge时,使用pipe来获得编译的输出结果。

在使用ReadFile读管道时,当结果全部读完后,在调用ReadFile竟然一直阻塞,这着实让我纳闷了一阵。

反复试验后,发现在关闭hWritePipe后,函数读完就立即返回。

到晚上一查:

 The ReadFile function returns when one of the following conditions occur:


A write operation completes on the write end of the pipe.
The number of bytes requested is read.
An error occurs.

果然还是csdn没有理解透,先前我也考到这段文字,但是没有真正理解“A write operation completes on the write end of the pipe",看来,只有把hWritePipe关闭后,写操作才算完成。

贴出部分代码:

 


 HANDLE hReadPipe,
  hWritePipe;
 SECURITY_ATTRIBUTES sa;
 sa.nLength = sizeof(sa);
 sa.bInheritHandle = TRUE;
 sa.lpSecurityDescriptor = NULL;
 bRet = CreatePipe(&hReadPipe, &hWritePipe, &sa, 1024);
 if(!bRet)
 {
  debug("Create compiler pipe error:%X/n", GetLastError());
  return E_COMPILER_COF;
 }

 // Compiler process StarupInfo
 STARTUPINFO StartupInfo;
 GetStartupInfo(&StartupInfo);
 StartupInfo.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
 StartupInfo.wShowWindow = SW_HIDE;  
 StartupInfo.cb = sizeof(STARTUPINFO);
 StartupInfo.hStdOutput = hWritePipe;
 StartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
 StartupInfo.hStdError = hWritePipe;

 char* ptr = strrchr(szCodePath, '//');
 if(ptr)
 {
  char* it = szCodePath;
  while(it != ptr && *it != '/0 ')
  {
   *(szCurrentDirectory + (int)(it - szCodePath)) = *it;
   it ++;
  }
  debug("CurrentDirectory:%s/n", szCurrentDirectory);
  SetCurrentDirectory((LPCSTR)szCurrentDirectory);
 }
 PROCESS_INFORMATION ProcessInfo;
 bRet = CreateProcess(NULL, (LPTSTR)pCmd, NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS, NULL, NULL, &StartupInfo, &ProcessInfo);
 if(!bRet)
 {
  return E_COMPILER_CP;
 }
 DWORD dwExitCode;
 DWORD dwRet = WaitForSingleObject(ProcessInfo.hProcess, Settings::dwWaitForComipilerTime);

 
 if(dwRet != WAIT_OBJECT_0 && !GetExitCodeProcess(ProcessInfo.hProcess, &dwExitCode))
 {
  if(dwRet == WAIT_TIMEOUT)
  {
   return E_COMPILER_TO;
  }
  return E_COMPILER_RF;
 }
 debug("Compiler exit code: %d", dwExitCode);
 CloseHandle(ProcessInfo.hProcess);
 CloseHandle(ProcessInfo.hThread);
 CloseHandle(hWritePipe);     //A write operation completes on the write end of the pipe.

 char buffer[1024] = {0};
 DWORD dwRead;
 while(ReadFile(hReadPipe, (LPVOID)buffer, sizeof(buffer) - 1, &dwRead, NULL) && dwRead > 0)
 {
  printf(buffer);
  memset(buffer, 0, sizeof(buffer));
 }
 
 if(dwExitCode == E_UNKNOWN)
 {
  return E_COMPILER_CE;
 }

 CloseHandle(hReadPipe);

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值