我正在尝试关注这篇 msdn 文章。
我创建了一个非常简单的控制台应用程序。
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;
任何建议......不幸的是,这篇文章也没有帮助。