Re: How to handle input and output of a program executed by System function in perl

510046470588-0001_at_t-online.de
Date: 07/20/04


Date: 20 Jul 2004 08:50:48 +0200

zw@cs.man.ac.uk (zw) writes:
>
> Hi,
> I think Perl is good at dealing with system functions like other
> scripting languages do. But I am not sure how does it handle inputs
> and outputs from
> external programs? for example,
> system "java Foo arg1 arg2";
> Can I assign the result returned by Foo.java to a variable like
> $a = system "java Foo arg1 arg2";

the simplest way is
$a = `java Foo arg1 arg2`;

another example is
$s = `cat filename`;
for retrieving the content of an external file, when cat is the
unix command.

in array context, this approach splits the output string into lines.

a safer way would use the functions fork, exec, and pipe for starting
the external programm and indirecting its output into a file handle.

if the program reads or writes (but not both) continually from Stdin/out,
the open function may be used with a pipe.

bidirectional communication, as needed when e.g. writing a perltk interface
to a command line interpreter like octave, is more difficult,
as it has deadlocks coming if not handled carefully.
IPC::Open2 may help, or IO::Pty ;

Klaus Schilling



Relevant Pages

  • Re: Literal pipes in [open "|cmd..."]
    ... it only applied to "exec" (by introducing ... a quote-char, and for each that is, *at most one* such ... pipe would still be taken as a pipe. ... to pass through arbitrary strings to external programs. ...
    (comp.lang.tcl)
  • Re: Building a pipe "by hand" in C?
    ... What I don't like about this is that this solution relies on the ... existence of a shell -- but it also relies on other external programs, ... Call pipe(). ... You now have four file descriptors, ...
    (comp.unix.programmer)
  • Re: Thread reading from a pipe blocks other threads, why?
    ... I'm implementing an application where the main Ruby program spawns off a ... number of external programs using pipes. ... Each pipe is handled by its own ... puts "BG Thread" ...
    (comp.lang.ruby)
  • Thread reading from a pipe blocks other threads, why?
    ... I'm implementing an application where the main Ruby program spawns off ... a number of external programs using pipes. ... since noone consumes anything in the pipe. ... puts "BG Thread" ...
    (comp.lang.ruby)