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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.