if not CreateProcess(nil, // lpApplicationName: PChar PChar(CmdLine), // lpCommandLine: PChar nil, // lpProcessAttributes: PSecurityAttributes nil, // lpThreadAttributes: PSecurityAttributes True, // bInheritHandles: BOOL CREATE_NEW_CONSOLE, nil, PChar(WorkDir), StartInfo, ProcInfo) then begin raise Exception.Create(SysErrorMessage(GetLastError)); end; try WaitForSingleObject(ProcInfo.hProcess, INFINITE);
HandleStream := THandleStream.Create(StdOutRead); try if HandleStream.Size > 0 then begin RetStrs := TStringList.Create; try RetStrs.LoadFromStream(HandleStream); Result := RetStrs.Text; finally RetStrs.Free; end; end; finally HandleStream.Free; end;
if not GetExitCodeProcess(ProcInfo.hProcess, ExitCode) then begin raise Exception.Create(SysErrorMessage(GetLastError)); end; if ExitCode <> 0 then begin raise Exception.Create(Result); end; finally CloseHandle(ProcInfo.hThread); CloseHandle(ProcInfo.hProcess); end; end;
begin Result := ''; FillChar(SA, sizeof(SA), 0); // 设置允许继承,否则在NT和2000下无法取得输出结果 SA.nLength := sizeof(SA); SA.bInheritHandle := True; SA.lpSecurityDescriptor := nil;
if not CreatePipe(StdOutRead, StdOutWrite, @SA, 0) then begin raise Exception.Create(SysErrorMessage(GetLastError)); end; try if Length(stdin) <> 0 then begin if not CreatePipe(StdInRead, StdInWrite, @SA, 0) then begin raise Exception.Create(SysErrorMessage(GetLastError)); end; try HandleStream := THandleStream.Create(StdInWrite); try StringStream := TStringStream.Create(stdin); try HandleStream.CopyFrom(StringStream, 0); finally StringStream.Free; end; finally HandleStream.Free; end;