Skip to main content.
home | support | download

Back to List Archive

Re: Running programs on Windows

From: Anthony Baratta <anthony(at)not-real.2plus2partners.com>
Date: Wed Sep 29 2004 - 20:11:14 GMT
I also found a code example using fork() here:

http://www.steve.gb.com/perl/lesson12.html

I hacked it with an outer loop to run the fork() more than 64 time, in 
batches of 5. Seems to not blow up. But that does mean I understand it any 
better. ;-)

e.g. without the outer loop, if increase the loop to greater than 64, it 
blows. If I give it time to reap the sub-processes, then it seems to clean 
up enough to keep running beyond 64 forks - albeit in chunks less than 64.

I hope this helps. I'm still reading on the Win32::Process::Create(), not 
sure if it's any better than trying to use the windows pseudo fork function.



#!/C:\perl\bin\perl.exe
use strict;
use warnings;
$| = 1; # turn off buffering
my $forks = 0;
MAIN: for ( 1 .. 20)
{
     my $pid = $$; # $$ holds the current process ID number
     my $parent = 0; # the original process was an immaculate conception
     my @kids = (); # no babies yet

     FORKER: for ( 1 .. 5 )
     {
         my $newpid = fork();
         if ( not defined $newpid )
         {
             # if return value of fork() is undef, something went wrong
             die "fork didn't work: $!\n";
         }
         elsif ( $newpid == 0 )
         {
             $forks++;
             # if return value is 0, this is the child process
             $parent = $pid; # which has a parent called $pid
             $pid = $$;      # and which will have a process ID of its very own
             @kids = ();     # the child doesn't want this baggage from the 
parent
             last FORKER;    # and we don't want the child making babies either
         }
         else
         {
             # the parent process is returned the PID of the newborn by fork()
             print "$$ spawned $newpid\n";
             push @kids, $newpid;
         }
     }
     if ( $parent ) # if I have a parent, i.e. if I'm the child process
     {
         print "I am process number $pid and I have generated this random 
number ",
             int rand 10, " for you\n";
         exit( 0 );
     }
     else
     {
         # parent process needs to preside over the death of its kids
         while ( my $kid = shift @kids )
         {
             print "Parent waiting for $kid to die\n";
             my $reaped = waitpid( $kid, 0 );
             unless ( $reaped == $kid )
             {
                 print "Something's up: $?\n";
             }
         }
     }
}
Received on Wed Sep 29 13:11:37 2004