来自管道的Readfile被阻止

时间:2014-10-10 12:51:10

标签: delphi readfile

在下面的代码中,我使用" commandLine"创建另一个进程的参数,但是这个子进程可能没有写入管道,所以readfile函数会阻塞 如果没有数据,如何让它返回?

if (CreateProcess(nil, PChar('cmd.exe /C ' + CommandLine), @saSecurity, @saSecurity, True, NORMAL_PRIORITY_CLASS, nil, nil, suiStartup, piProcess))
  then
    sOutputString := '';
  begin

    repeat

      dRunning := WaitForSingleObject(piProcess.hProcess, 100);
      Application.ProcessMessages();

    until (dRunning <> WAIT_TIMEOUT);

    CloseHandle(piProcess.hProcess);
    CloseHandle(piProcess.hThread);

    repeat
      dRead := 0;

      ReadFile(hRead, pBuffer[0], CReadBuffer, dRead, nil);
      // But it is blocked......

    until (dRead < CReadBuffer);

  end;

1 个答案:

答案 0 :(得分:2)

您可以在读取之前检查命名管道是否包含数据

if PeekNamedPipe(hRead, nil, 0, nil, @dwBytesAvailable, nil) then
begin
   if dwBytesAvailable > 0 then
   begin
      ReadFile(...);
   end;
end;