If I've got this right, your code is already prevented from being a fork bomb. Your script forks off a single child, then waits for that child to terminate, before forking off the next child. :) I don't think that's what you were looking for, though...
According to the docs for wait and waitpid, the status of the child process is returned in $?. Thus, your child can exit with a status code to indicate whether it succeeded, and the parent can use that to determine whether or not to increment $avail.
Here's a quick example based on some code from perlipc. (Please note that prior to 5.6.0 the relevant code sample in perlipc omitted the > 0 in the while condition.)
#!/usr/local/bin/perl -w
use strict;
use POSIX ":sys_wait_h";
my $avail;
sub REAPER {
my $child;
while ($child = waitpid(-1,&WNOHANG()) > 0) {
$avail += ! $?; # 0 means success, non-zero means failure
}
$SIG{CHLD} = \&REAPER;
}
$SIG{CHLD} = \&REAPER;
for (0..2,0..2) {
if (fork) {
} else {
exit $_;
}
}
print "$avail\n";
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.