Perl:fork 创建新的 PID,但父级不继续



我正在尝试编写一些代码来执行长时间运行的进程(用睡眠模拟,实际上是对数据库存储过程的调用(并等待它完成,同时异步打印更新。

以下是我到目前为止所拥有的...

法典。。。

#!/usr/bin/perl
use strict;
use warnings;
use 5.8.8;
my $pid1 = fork();
if( $pid1 == 0 ){
print "starting long running process: $$n";
foreach (1..10) {
sleep 1;
print "sleep $_n";
}   
print "completed long running processn";
exit 0;
}
print "making sure long running process is complete: $$n";
while (1) {
my $child = waitpid(-1, 0); 
last if $child eq -1; 
print "$child is still runningn";
sleep 1;
}
print "child PID:$pid1. Process has now completed: $$n";
exit 0;

输出。。。。

making sure long running process is complete: 27280
starting long running process: 27281
sleep 1
sleep 2
sleep 3
sleep 4
sleep 5
sleep 6
sleep 7
sleep 8
sleep 9
sleep 10
completed long running process
27281 is still running
child PID:27281. Process has now completed: 27280

所以我可以看到已经创建了一个子进程,但为什么我的"仍在运行"消息直到子进程完成后才打印出来?(我期待其中的 9/10,但只得到一个(

因为waitpid($pid, 0)在收获进程或确定没有更多子进程要收获之前不会返回。

如果要执行非阻塞等待,请使用WNOHANG标志,因为 perldoc 解释道:

use POSIX ':sys_wait_h';
...
while (1) {
my $child = waitpid(-1, WNOHANG); 
last if $child eq -1; 
print "$pid1 is still runningn";
sleep 1;
}

最新更新