[sf-perl] Spawning external program within Perl

Joseph Brenner doom at kzsu.stanford.edu
Wed Nov 8 12:35:51 PST 2006


David Fetter <david at fetter.org> wrote:

> Loo, Peter wrote:

> >    I was wondering if there is a built-in Perl module that would allow me to
> >    spawn  an external program and not wait for it to complete.  What I am
> >    attempting to do is, I am checking within a database for a condition and
> >    when  the  condition  is met, I want to call an external Perl program.
> >    However, I don't want to wait for the external program to complete before
> >    moving on to my next step within my program.
> 
> About ten seconds of searching with perldoc -q led me to 
> 
> perldoc -f exec

But exec isn't what he needs if he doesn't want to wait for completion. 

The popular suggestion here of doing a manual "fork" is a good way of
doing it (Perl Cookbook, 2nd ed. recipie 16.10), but it might be simpler 
to just open to a pipe (Perl Cookbook, 2nd ed. recipie 16.4).

  $pid = open $external, "|-", "program", "arguments" 
     or die "Couldn't fork: $!\n";

  print $external "Send this info to external program's STDIN\n";
  close $external;

Knowing which M to RTFM is always the trick, eh?
   perldoc perlopentut
   perldoc -f open
   perldoc perlfaq8

Checking my memory of how this works, I see that it's important to have
an ampersand on the end of the "program" string if you don't want it to
block.  

Just as an example, here's a script that simultaneously pops open three
terminal windows ('rxvt') showing three different websites:

   #!/usr/bin/perl
   #show3lynx

   my @sites = qw(
     http://alterslash.org
     http://news.google.com
     http://perlmonks.org
   );
   
   foreach my $url (@sites) { 
     my $cmd  = "rxvt -e lynx '$url' &";
     open my $ext, "|-", $cmd 
        or die "Couldn't fork: $!\n";
   }
   
--
(Hmm... bye bye Rummie.)   


More information about the SanFrancisco-pm mailing list