Here is some sample of how to do that:
But note that is very recomended to use threads directly, and make your program based on thread architecture. But you will need to work on Perl-5.8.0, where thread works fine. With threads you have more resources, specially the shared variables!#!/usr/bin/perl ## Init the detached codes: sub DETACH_INIT { my ( $x ) = @_ ; $| = 1 ; ## Flush STDOUT or will lock some threads on Win32. $SIG{CHLD} = \&REAPER ; ## Who will lead with childs on real fork. ## Run $x times the detached codes: my $wpid = 0 ; for my $i (1..$x) { next if $wpid ; ## Next until the wait() is on. &SPAWN($i) ; } ## Wait for the childs. sub REAPER{ $wpid = wait ; $SIG{CHLD} = \&REAPER ; } ## Make the fork, start the detached code, than continue main code. ## When the detached code return, make an exit of the forked process + or thread. sub SPAWN { my ( $id ) = @_ ; my $pid ; if (!defined($pid = fork)) { print "cannot fork: $!\n" ; return ;} elsif ($pid) { return ;} exit &DETACHED_CODE($id) ; } } ## Code to be runned detached: sub DETACHED_CODE { my ( $id ) = @_ ; for(0..10) { print "$id>> $_\n" ; sleep(1); } } ## Tell to start 2 detached codes: &DETACH_INIT(2) ; ## Some main code to continue: for(0..10) { print "main>> $_\n" ; sleep(1); }
Note, use Perl-5.6.1++ for fork(), specially on Win32.
Update (execution of other process):
To execute other scripts from Perl, use open:
If you skip the close you don't wait the process to return:my $cmd = "$^X foo.pl arg1" ; ## $^X is the path to perl(.exe) interpr +eter. open (CMDLOG,"| $cmd") ; close (CMDLOG) ;
open (CMDLOG,"| $cmd") ; ## Now you can continue your main (caller) script...
Or just use the Open3 from IPC to get the retuned data to the pipe:
This 2 ways are very portable, at least between Win32 and Linux. The first (open) is more.use IPC::Open3 ; my $cmd = "$^X foo.pl arg1" ; open3(LOGREAD , LOGERROR, LOGWRITE, "$cmd"); my @log = (<LOGREAD> , <LOGERROR>) ; close(LOGREAD , LOGERROR, LOGWRITE) ; print "@log\n" ;
Other thing, try to use different HANDLES (like CMDLOG) for multi calls when you don't use the close(). For example:
open (CMDLOG1,"| $cmd1") ; open (CMDLOG2,"| $cmd2") ; open (CMDLOG3,"| $cmd3") ;
Graciliano M. P.
"The creativity is the expression of the liberty".
In reply to Re: spawning Perl scripts (Win32/Linux sample)
by gmpassos
in thread spawning Perl scripts
by awkmonk
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |