Perl: Running two processes at once.

Forum Index » Forums » Programming and Development
Author Message
Joined: Jan 05, 2009
Posts: 2
Other Topics
Posted Jan 06, 2009 at 8:09:25 PM
Subject: Perl: Running two processes at once.
I am writing a perl script and at one point I would like to run two executables at once. If I do two system calls then I have to wait until the first process finishes to start the second. Is there a way around this?
Back to top Profile Email Website
thobbs
Joined Oct 12, 2008
Posts: 238
Location:Texas!

Other Topics
Posted: Jan 06, 2009 10:05:42 PM
I would use fork(). If you've never forked a program before, you should read up on the basics, but this is basically how to do it:[code=xml]$pid = fork(); if($pid == 0) { # Fork returns 0 to the child, and the child's pid to the parent execute child's code exit 0; # The child will exit at this point } execute parent's code exit 0;[/code]Anyways, like I said, definitely read up on forking.
Back to top Profile Email Website
Mr. Shawn H. Corey
Joined Jun 21, 2007
Posts: 2

Other Topics
Posted: Jan 07, 2009 2:36:43 PM
Here's the sub I use: [code=xml]# -------------------------------------- # 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; } [/code]
Back to top Profile Email
Forum Index » Forums » Programming and Development