On Fri, 2009-01-16 at 20:11 +0530, Sharan Basappa wrote:
> Hi,
> 
> What is the method to launch unix process from perl. I believe this is
> going to be system call.
> The additional requirement I have is that the calls should be non
> blocking mainly as these
> process execution should happen in parallel.
> 
> Regards,
> Sharan
> 

You have to use fork and exec; see `perldoc -f fork` and `perldoc -f
exec`

Here is the sub I use:
# --------------------------------------
#      Usage: $child_pid = fork_exec( \%control, $command; @arguments );
#    Purpose: Fork and exec the command
# Parameters:  \%control -- optional control hash ref
#                             -nohup -- non-zero means parent won't wait for 
child completion
#                            -system -- non-zero means use system if cannot fork
#                             -quiet -- non-zero means close STD... file handles
#               $command -- system command
#             @arguments -- optional list of arguments for command
#    Returns: $child_pid -- or undef if failure
#
sub fork_exec {
  my %control = ();
  if( my $ref = ref( $_[0] ) ){
    if( $ref eq 'HASH' ){
      %control = %{ shift @_ };
    }
  }

  my $command   = shift @_;
  my @arguments = @_;

  my $child_pid = fork();
  unless( defined $child_pid ){
    if( $control{-system} ){
      system( "nohup $command @arguments &" );
    }
    return;
  }

  unless( $child_pid ){
    # child
    if( $control{-quiet} ){
      close STDIN;
      close STDOUT;
      close STDERR;
      open STDERR, '>', '/dev/null';
    }
    $SIG{HUP} = 'IGNORE' if $control{-nohup};
    exec { $command } $command, @arguments or do {
      if( $control{-system} ){
        system( "nohup $command @arguments &" );
      }
      return;
    }
  }

  # parent
  return $child_pid;
}


-- 
Just my 0.00000002 million dollars worth,
  Shawn

Programming is as much about organization and communication
as it is about coding.

"It would appear that we have reached the limits of what it is
 possible to achieve with computer technology, although one should
 be careful with such statements, as they tend to sound pretty silly
 in 5 years."
   --John von Neumann, circa 1950


-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to