Personally I try to avoid the use of signals in
cases like this because they are dangerous in old perls and
hard to get racefree in new perls (you need to take care of
the case that a process exits before you properly stored the
pid).
Instead of that I usually try to have a pipe into the
processes and poll/select on them. Most programs don't close
the standard handles, so you can actually use these. In
this case I use STDIN.
The following code demonstrates the idea. Modify it to fit whatever your constraints are.
#! /usr/bin/perl -w
use 5.008;
use strict;
use IO::Select;
# program and args
my @work = qw(sleep 3);
my $wanted = 2;
my $s = IO::Select->new;
my $have = 0;
while ($wanted) {
while ($have < $wanted) {
open(my $fh, "|-", @work) || die "Could not fork: $!";
$s->add($fh);
$have++;
}
for ($s->can_read()) {
$s->remove($_);
$have--;
close $_;
die "Unexpected returncode $?" if $?;
# Real code may change $wanted here
}
}
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.