This perl script tests the use of fork(). I inadvertantly discovered that adding the problem code causes oddities with process id's, wait's, and such. When the problem code is uncommented, the child count goes to -1 instead of 0. I would greatly appreciate an explanation of why get_pidof() screws up wait().

Thank you.
#!/usr/bin/perl -w use strict; use Unix::PID; ## problem code: my $pid = Unix::PID->new(); #my @pids = $pid->get_pidof('fork.pl'); #die "one copy of me is already running\n" if scalar(@pids) > 0; ## :problem code print "<parent>: my process id: $$\n"; my $childcnt = 0; foreach my $process (@ARGV) { my $pid = fork; if (defined $pid ) { if ($pid ) { # parent process if (++$childcnt >= 2) { # hit child limit print "<parent>: must wait to start more\n"; my $completed_pid = wait; $childcnt--; print "<parent>: $completed_pid is done; $childcnt run +ning\n"; } else { # more children ok print "<parent>: $childcnt running; can start more\n"; } } else { # child process print "<$process>: my id: $$\n"; sleep int(rand(10)); print "<$process>: end: $$\n"; exit 0; } } else { # fork failed warn "<parent>: fork failed $!\n"; last; } } print "<parent>: waiting for $childcnt to complete\n"; until ((my $completed_pid = wait) == -1) { $childcnt--; print "<parent>: $completed_pid is done; $childcnt running\n"; }; print "<parent>: complete; $childcnt process(es) left\n";

In reply to get_pidof() messes with wait()? by rhumbliner

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.