[Lazarus] Reading from an external process

Richard Mace richard.mace at gmail.com
Tue Nov 5 14:48:42 CET 2013


Hi All,
I have got the following code from the wiki for creating and reading from
an external process. Effectively, I want to capture all of the output from
the process "handle.exe", into a StringList so that I can read it to make
sure that everything went OK, however, when I run the following code, I am
getting a "RunError(103) on the line: WriteLn('-- Going to run: ' +
OurCommand);

Any ideas what I'm doing wrong please?

Lazarus 1.0.12 with FPC 2.6.2 Windows XP

procedure TfrmMain.Button1Click(Sender: TObject);
const
  READ_BYTES = 2048;

var
  OurCommand: String;
  OutputLines: TStringList;
  MemStream: TMemoryStream;
  OurProcess: TProcess;
  NumBytes: LongInt;
  BytesRead: LongInt;

begin
  MemStream := TMemoryStream.Create;
  BytesRead := 0;

  OurProcess := TProcess.Create(nil);
  OurCommand:='C:\Documents and Settings\RichardMace\My
Documents\Downloads\SysinternalsSuite\handle.exe';
  WriteLn('-- Going to run: ' + OurCommand);
  OurProcess.CommandLine := OurCommand;

  OurProcess.Options := [poUsePipes];
  WriteLn('-- External program run started');

  OurProcess.Execute;
  while OurProcess.Running do
  begin
    // make sure we have room
    MemStream.SetSize(BytesRead + READ_BYTES);

    // try reading it
    NumBytes := OurProcess.Output.Read((MemStream.Memory + BytesRead)^,
READ_BYTES);
    if NumBytes > 0 then
      begin
        Inc(BytesRead, NumBytes);
        Write('.'); //Output progress to screen.
      end
    else begin
      // no data, wait 100 ms
      Sleep(100);
    end;
  end;
  // read last part
  repeat
    // make sure we have room
    MemStream.SetSize(BytesRead + READ_BYTES);
    // try reading it
    NumBytes := OurProcess.Output.Read((MemStream.Memory + BytesRead)^,
READ_BYTES);
    if NumBytes > 0 then
      begin
        Inc(BytesRead, NumBytes);
        Write('.');
      end;
  until NumBytes <= 0;
  if BytesRead > 0 then WriteLn;
  MemStream.SetSize(BytesRead);
  memMain.Lines.Add('-- External program run complete');

  OutputLines := TStringList.Create;
  OutputLines.LoadFromStream(MemStream);
  memMain.Lines.Add('-- External program output line count = ' +
IntToStr(OutputLines.Count) + ' --');
  for NumBytes := 0 to OutputLines.Count - 1 do
    begin
      WriteLn(OutputLines[NumBytes]);
    end;
  WriteLn('-- Program end');
  OutputLines.Free;
  OurProcess.Free;
  MemStream.Free;
end;
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lazarus-ide.org/pipermail/lazarus/attachments/20131105/a0ac81b7/attachment-0002.html>


More information about the Lazarus mailing list