{
Copyright (C) 1999 Free Software Foundation, Inc.

Author: Frank Heckenbach <frank@pascal.gnu.de>

Demo program for the Pipe unit

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 2.

This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
for more details.

You should have received a copy of the GNU General Public License
along with this program; see the file COPYING.  If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA.
}

program PipeDemo;

uses GPC, Pipe;

var
  ToInput, FromOutput, FromStdErr : Text;
  c : Char;

{ Check for output while reading input. Don't read more than a character
  at a time, because trying to read more might block, and since we are
  just writing data to the process as well, cause a deadlock! }
procedure CheckProcessOutput;
begin
  while DataReady (FromOutput) do
    begin
      if EOLn (FromOutput) then Writeln else Write (':', FromOutput^, ':');
      Read (FromOutput, c)
    end;
  while DataReady (FromStdErr) do
    begin
      if EOLn (FromStdErr) then Writeln else Write ('_', FromStdErr^, '_');
      Read (FromStdErr, c)
    end
end;

begin
  { Start a process with pipes }
  Pipe (ToInput, FromOutput, FromStdErr, 'demoproc', null, Environment);
  if IOResult <> 0 then
    begin
      Writeln (StdErr, 'Could not create pipe to `demoproc''. Please compile `demoproc.pas'' first,');
      Writeln (StdErr, 'and make sure the resulting executable can be found in your PATH.');
      Halt (1)
    end;

  { Pipe some input to the process }
  Writeln (ToInput, 'foo');
  CheckProcessOutput;
  Writeln (ToInput, 'bar');
  CheckProcessOutput;

  Close (ToInput); { It's important to close ToInput here, so the process
    will terminate. However, the effect of not closing ToInput are quite
    different under Unix (waiting for more input from FromOutput or
    FromStdErr) and Dos (never starting the process in the first place
    and therefore not getting any data from FromOutput and FromStdErr!). }

  { Read all the remaining output }
  repeat
    CheckProcessOutput
  until EOF (FromOutput) and EOF (FromStdErr)
end.
