Here is some code for you to have a look at. It forks 5 kids. One to process each of the dirs in @dirs. It then waits for them to finish and dies.
So to answer your specific questions
1) you can fork lots of processes - each has a overhead in starting so sometimes more is less and sometimes less is more if you get my drift. The longer each kid will take to run the more worthwhile it is to fork them off.
2) Either code it so you get the number of processes you want or see Parallel::ForkManager vs global variables for a bit of info on this module (it allows you to set an upper limit on processes)
3) You wait on kids as shown below:
#!/usr/bin/perl -w use strict; use POSIX ":sys_wait_h"; $|++; # flush buffers my @dirs = qw ( dir1 dir2 dir3 dir4 dir5 ); my @pids; for my $dir (@dirs) { my $pid = fork(); die "Fork failed" unless defined $pid; push @pids, $pid; next if $pid; # parent returns to loop # child starts here do_dir($dir); exit; # kill child here after it has done work } print "Child pids are:\n"; print "$_\n" for @pids; # wait for all kids to finish my $kids; do{ $kids = waitpid(-1, &WNOHANG); }until $kids == -1; print "My children are all dead!\n"; print "My life is not worth living....\n"; die "I can go on no longer\nGoodbye cruel CPU\n"; sub do_dir { my $dirname = shift; # do dir stuff # we will exit on return sleep ( 2+ rand 5); # simulate processing print "Processed $dirname\n"; }
cheers
tachyon
s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print
In reply to Re: Help with waitpid and forking ?
by tachyon
in thread Help with waitpid and forking ?
by VicBalta
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |