Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Re: Re: forking through a subroutine

by leons (Pilgrim)
on Apr 10, 2001 at 12:41 UTC ( [id://71285] : note . print w/replies, xml ) Need Help??

in reply to Re: forking through a subroutine
in thread forking through a subroutine


I'm writing something similar as well at this moment which
might come in handy.

You can pass a reference to a sub and it's parameters to the
spawnChild sub, which will provide you with it's PID and
a filehandler to the child.

It's all still very basic and nothing fancy, that's because I'm
doing lots of learning and testing right now ... but it works ;-)

#!/usr/bin/perl -w use strict; # # Declaration of Subroutines # sub spawnChild(@); # # Main # my ($pid,$fh)=spawnChild(\&Count,10); print "$pid\n"; # # Subroutines # sub spawnChild(@) { my $childSub=shift; my @Parameters=@_; my ($Cnt,$pid)=0; do { $pid=open FH,'-|'; unless (defined $pid) { warn "Cannot fork: $!\n"; die "Could not fork\n" if $Cnt++ > 5; sleep 10; } } until defined $pid; if ($pid) { #Parent return($pid,*{FH}); } else { #Child; &$childSub(@Parameters); exit(0); } } sub Count($) { foreach(1..shift) { print "$_\n"; sleep(1); } }

Bye, Leon