I am having an issue with capturing the return status of the child process. below is a simplified version of my code.
use Modern::Perl;
use POSIX;
use AnyEvent;
my @jobs = (1, 7, 3, 9 , 4 , 2);
my %pid;
my %running;
my $t = AE::timer 0, 5, sub{
while(scalar( keys %running < 3) && scalar (@jobs)){
my $job = shift @jobs;
$running{$job}=1;
$pid{$job} = run($job);
}
for(keys %running){
delete $running{$_} unless check($pid{$_},$_);
}
exit unless scalar keys %running;
};
AnyEvent->condvar->recv;
sub func_to_run{
my $id = shift;
close STDOUT;
open STDOUT, ">>$id.log";
exec '/bin/sleep', $id;
}
sub run{
my $id = shift;
print "starting job $id\n";
my $pid = fork();
return $pid if $pid;
func_to_run($id);
}
sub check{
my ($pid,$id) = @_;
my $result = waitpid($pid, WNOHANG);
{
if ($result == $pid) {
my $rc = $? >> 8;
print "Job $id finished with code $rc\n";
return 0;
}
elsif ($result == -1 and $! == ECHILD) {
print "Job $id finished running, not sure if it was sucessfull\n";
return 0;
}
elsif ($result == 0) {
return 1;
}
redo;
}
}
OUTPUT:
starting job 1
starting job 7
starting job 3
Job 1 finished running, not sure if it was sucessfull
Job 3 finished running, not sure if it was sucessfull
starting job 9
starting job 4
Job 7 finished running, not sure if it was sucessfull
starting job 2
Job 4 finished running, not sure if it was sucessfull
Job 9 finished running, not sure if it was sucessfull
Job 2 finished running, not sure if it was sucessfull
why is waitpid() returning -1 instead of a return status?
EDIT: I changed system + exit to exec. This was what I was originally doing. My goal is to be able to signal the child process, which I don't actually think can be done with system.
kill($pid,'HUP');
EDIT 2: There can be several child processes running at once, and this is being called from a AE::timer module. what I want to figure out here is why I am getting -1 from waitpid() which indicates that the child was reaped.
EDIT 3: I have changed the code to a full working example with the output I get