我在捕获子进程的返回状态时遇到问题。下面是我的代码的简化版本。
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;
}
}
输出:
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
为什么 waitpid() 返回 -1 而不是返回状态?
编辑:我将 system + exit 更改为 exec。这就是我最初所做的。我的目标是能够向子进程发出信号,实际上我认为 system.js 无法做到这一点。
kill($pid,'HUP');
编辑 2:可以同时运行多个子进程,这是从 AE::timer 模块调用的。我想在这里弄清楚为什么我从 waitpid() 得到-1,这表明孩子被收割了。
编辑 3:我已将代码更改为完整的工作示例,并得到输出