CreateProcess,PowerShell和WaitForSingleObject

时间:2016-07-22 17:01:46

标签: delphi

我正在使用管道来获取程序中的cmd.exe输出。有时,我注意到如果cmd.exe要求用户输入(我创建隐藏的cmd窗口),程序会挂起,因为没有人会将输入放在窗口中,而cmd将会保留。所以我实现了WaitForSingleObject以避免挂起cmd要求用户输入或只是因为其他原因挂起的情况。当我尝试执行powershell命令时会出现问题,因为它看起来对WaitForSingleObject没有响应,而且我总是达到超时。功能是:

function GetDosOutput(const Exe, Param: string): string;
const
  InheritHandleSecurityAttributes: TSecurityAttributes =
    (nLength: SizeOf(TSecurityAttributes); bInheritHandle: True);
var
  hReadStdout, hWriteStdout: THandle;
  si: TStartupInfo;
  pi: TProcessInformation;
  WaitTimeout, BytesRead: DWord;
  lReadFile: boolean;
  Buffer: array[0..255] of AnsiChar;
begin
  Result:= '';
  if CreatePipe(hReadStdout, hWriteStdout, @InheritHandleSecurityAttributes, 0) then
  begin
    try
      si:= Default(TStartupInfo);
      si.cb:= SizeOf(TStartupInfo);
      si.dwFlags:= STARTF_USESTDHANDLES;
      si.hStdOutput:= hWriteStdout;
      si.hStdError:= hWriteStdout;
      if CreateProcess(Nil, PChar(Exe + ' ' + Param), Nil, Nil, True, CREATE_NO_WINDOW,
                        Nil, PChar(ExtractFilePath(ParamStr(0))), si, pi) then
      begin
        CloseHandle(hWriteStdout);
        while True do
        begin
          try
            WaitTimeout:= WaitForSingleObject(pi.hProcess, 20000);
            if WaitTimeout = WAIT_TIMEOUT then
            begin
              Result:= 'No result available';
              break;
            end
            else
            begin
              repeat
                lReadFile:= ReadFile(hReadStdout, Buffer, SizeOf(Buffer) - 1, BytesRead, nil);
                if BytesRead > 0 then
                begin
                  Buffer[BytesRead]:= #0;
                  OemToAnsi(Buffer, Buffer);
                  Result:= Result + String(Buffer);
                end;
              until not (lReadFile) or (BytesRead = 0);
            end;
            if WaitTimeout = WAIT_OBJECT_0 then
              break;
          finally
            CloseHandle(pi.hProcess);
            CloseHandle(pi.hThread);
          end;
        end;
      end;
    finally
      CloseHandle(hReadStdout);
    end;
  end;
end;

如果我调用此函数传递:

  

cmd.exe / C dir c:\

没关系。但如果我打电话使用:

  

powershell目录c:\ cmd.exe / C powershell目录c:\

WaitForSingleObject达到超时,没有任何反应。对此有何帮助?

1 个答案:

答案 0 :(得分:2)

管道的缓冲区可能已满。子进程被阻塞,等待您的进程从管道读取并为更多输出腾出空间。但是,您的程序也会被阻止,等待子进程完成。因此,僵局。

你需要继续读取管道,但问题是,如果你调用ReadFile并且进程因完整管道缓冲区之外的其他原因而挂起,那么你的程序也会挂起。 ReadFile没有提供超时参数。

ReadFile没有超时参数,因为异步读取是使用重叠I / O 完成的。您传递到ReadFile包含Windows事件句柄的TOverlapped记录。 ReadFile将立即返回,并在读取完成时发出事件信号。使用WaitForMultipleObjects不仅要等待进程句柄,还要等待这个新的事件句柄。

但是,有一个障碍。 CreatePipe创建匿名管道,匿名管道不支持重叠I / O.因此,您必须使用CreateNamedPipe代替。在运行时为管道生成唯一的名称,因此它不会干扰任何其他程序(包括您的程序的其他实例)。

以下是代码如何运行的草图:

var
  Overlap: TOverlapped;
  WaitHandles: array[0..1] of THandle;
begin
  hReadStdout := CreateNamedPipe('\\.\pipe\unique-pipe-name-here',
    Pipe_Access_Inbound, File_Flag_First_Pipe_Instance or File_Flag_Overlapped,
    Pipe_Type_Byte or Pipe_Readmode_Byte, 1, x, y, 0, nil);
  Win32Check(hReadStdout <> Invalid_Handle_Value);
  try
    hWriteStdout := CreateFile('\\.\pipe\unique-pipe-name-here', Generic_Write,
      @InheritHandleSecurityAttributes, ...);
    Win32Check(hWriteStdout <> Invalid_Handle_Value);
    try
      si.hStdOutput := hWriteStdout;
      si.hStdError := hWriteStdout;
      Win32Check(CreateProcess(...));
    finally
      CloseHandle(hWriteStdout);
    end;
    try
      Overlap := Default(TOverlapped);
      Overlap.hEvent := CreateEvent(nil, True, False, nil);
      Win32Check(Overlap.hEvent <> 0);
      try
        WaitHandles[0] := Overlap.hEvent;
        WaitHandles[1] := pi.hProcess;
        repeat
          ReadResult := ReadFile(hReadStdout, ..., @Overlap);
          if ReadResult then begin
            // We read some data without waiting. Process it and go around again.
            SetString(NewResult, Buffer, BytesRead div SizeOf(Char));
            Result := Result + NewResult;
            continue;
          end;
          Win32Check(GetLastError = Error_IO_Pending);
          // We're reading asynchronously.
          WaitResult := WaitForMultipleObjects(Length(WaitHandles),
            @WaitHandles[0], False, 20000);
          case WaitResult of
            Wait_Object_0: begin
              // Something happened with the pipe.
              ReadResult := GetOverlappedResult(hReadStdout, @Overlap, @BytesRead, True);
              // May need to check for EOF or broken pipe here.
              Win32Check(ReadResult);
              SetString(NewResult, Buffer, BytesRead div SizeOf(Char));
              Result := Result + NewBuffer;
              ResetEvent(Overlap.hEvent);
            end;
            Wait_Object_0 + 1: begin
              // The process terminated. Cancel the I/O request and move on,
              // returning any data already in Result. (There's no further data
              // in the pipe, because if there were, WaitForMultipleObjects would
              // have returned Wait_Object_0 instead. The first signaled handle
              // determines the return value.
              CancelIO(hReadStdout);
              break;
            end;
            Wait_Timeout: begin
              // Timeout elapsed without receiving any more data.
              Result := 'no result available';
              break;
            end;
            Wait_Failed: Win32Check(False);
            else Assert(False);
          end;
        until False;
      finally
        CloseHandle(Overlap.hEvent);
      end;
    finally
      CloseHandle(pi.hProcess);
      CloseHandle(pi.hThread);
    end;
  finally
    CloseHandle(hReadStdout);
  end;
end;

请注意,在上面的代码中,程序的任何新输出都将基本上重置为完成该过程而分配的20秒超时。这可能是可以接受的行为,但如果没有,那么您必须跟踪已经过了多少时间并在调用WaitForMultipleObjects之前调整超时值(可能在调用{{1}之前)如果操作系统选择处理ReadFile非重叠的情况,也可以在调用它时已经有数据可用时执行此操作。

相关问题