Function ReadInputPipe(const Pipe: TInputPipeStream; var BytesRead,OutputLen: integer; var OutputString: string): Boolean;
var
available : integer;
NumBytes : integer;
begin
Result := False; available := 0;
if(BytesRead<0)then BytesRead := 0;
if(OutputLen<0)then OutputLen := 0;
repeat
if(Pipe=nil)then exit;
if(Pipe.NumBytesAvailable>0)
then available := Pipe.NumBytesAvailable
else break;
if(BytesRead+available>OutputLen)then
begin
OutputLen := BytesRead+READ_BYTES;
SetLength(OutputString,OutputLen);
end;
try
try
NumBytes := Pipe.Read(OutputString[1+BytesRead], available);
if(NumBytes>0)
then Inc(BytesRead, NumBytes);
except
Result := False;
end;
finally
Result := True;
end;
until false;
end;
Function __Runcommand(var P: TProcess; var Stdout, Stderr: string; var ExitStatus:integer): integer;
var
bytesread_stdout : integer;
outputlen_stdout : integer;
bytesread_stderr : integer;
outputlen_stderr : integer;
begin
Result := -1; if(P=nil)then exit;
try
try
P.Options := [poUsePipes];
bytesread_stdout := 0;
outputlen_stdout := 0;
bytesread_stderr := 0;
outputlen_stderr := 0;
P.Execute;
while(P.Running)do
begin
if(not ReadInputPipe(P.Output, bytesread_stdout, outputlen_stdout, Stdout))and
(not ReadInputPipe(P.Stderr, bytesread_stderr, outputlen_stderr, Stderr))
then sleep(100);
end;
//Get remaining output after end of execution:
ReadInputPipe(P.Output, bytesread_stdout, outputlen_stdout, Stdout);
ReadInputPipe(P.Stderr, bytesread_stderr, outputlen_stderr, Stderr);
ExitStatus := P.ExitStatus;
Result := 0; // we came to here, document that.
except
Result := 1;
end;
finally
FreeAndNil(P);
SetLength(Stdout,bytesread_stdout);
SetLength(Stderr,bytesread_stderr);
end;
end;
Function RunCommand(const ExeName:string;const Commands:array of string;var Stdout,StdErr:string): Boolean;
var
ExitStatus,i : integer;
P : TProcess;
begin
P := TProcess.Create(nil);
P.Executable := ExeName;
if high(commands)>=0
then for i:=low(Commands) to high(Commands)
do P.Parameters.Add(Commands[i]);
Result := (__RunCommand(P,StdOut,StdErr,ExitStatus)=0) and (ExitStatus=0);
end;