【问题标题】:Read from spawned process hangs both processes从衍生进程中读取会挂起两个进程
【发布时间】:2013-04-13 07:48:00
【问题描述】:

我正在尝试关注this msdn article

我创建了一个非常简单的控制台应用程序。

Writeln('Take a nap.');
Sleep(1000);
Writeln('Done.');

我正在使用以下代码启动控制台应用程序并(尝试)读取其输出。控制台应用程序和主应用程序都挂起。

procedure TForm1.Button1Click(Sender: TObject);
const
  PATH: WideString = 'c:\tmp\nap.exe';
var
  ProcInfo: TProcessInformation;
  StartInfo: TStartupInfo;
  WorkingDir: WideString;
  StdOutRead, StdOutWrite: THandle;
  Attr: SECURITY_ATTRIBUTES;
  N: Cardinal;
  Buf: Array [0.. 5000] of Byte;
begin
  FillChar(Attr, SizeOf(SECURITY_ATTRIBUTES), 0);
  Attr.nLength := SizeOf(SECURITY_ATTRIBUTES);
  Attr.bInheritHandle := True;
  Attr.lpSecurityDescriptor := nil;

  if not (CreatePipe(StdOutRead, StdOutWrite, @Attr, 0)) then
    RaiseLastOSError;

  FillChar(StartInfo, SizeOf(TStartupInfo), 0);
  StartInfo.cb := SizeOf(TStartupInfo);
  StartInfo.dwFlags := STARTF_USESTDHANDLES;
  StartInfo.hStdOutput := StdOutWrite;
  // I've tried creating pipes for stdin and stderr to no avail

  WorkingDir := ExtractFilePath(PATH);
  if not CreateProcess(nil, PWideChar(PATH), nil, nil, false, 0, nil, PWideChar(WorkingDir), StartInfo, ProcInfo) then
    RaiseLastOSError;

  // this call hangs -- the console app hangs regardless
  if not ReadFile(StdOutRead, Buf[0], Length(Buf), N, nil) then
    RaiseLastOSError;
end;

任何建议...不幸的是 this article 也没有帮助。

【问题讨论】:

标签: delphi winapi ipc


【解决方案1】:

我能看到的最明显的缺陷是你在调用CreateProcess 时将bInheritHandles 设置为False。您必须通过True,当您这样做时,您的代码将按预期工作。 nap.exe 的输出被忠实地读入Buf

【讨论】:

  • 谢谢...我不知道我是怎么错过的。
猜你喜欢
  • 1970-01-01
  • 2019-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-14
  • 1970-01-01
  • 2023-04-10
  • 2019-03-22
相关资源
最近更新 更多