#!/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);
}
####
my $cmd = "$^X foo.pl arg1" ; ## $^X is the path to perl(.exe) interpreter.
open (CMDLOG,"| $cmd") ; close (CMDLOG) ;
##
##
open (CMDLOG,"| $cmd") ;
## Now you can continue your main (caller) script...
##
##
use IPC::Open3 ;
my $cmd = "$^X foo.pl arg1" ;
open3(LOGREAD , LOGERROR, LOGWRITE, "$cmd");
my @log = ( , ) ;
close(LOGREAD , LOGERROR, LOGWRITE) ;
print "@log\n" ;
##
##
open (CMDLOG1,"| $cmd1") ;
open (CMDLOG2,"| $cmd2") ;
open (CMDLOG3,"| $cmd3") ;