参考文献1:https://stackoverflow.com/questions/40190657/linux-perl-fork-loop-without-exiting-child-process
参考文献2:https://perlmaven.com/fork
参考文献3:https://perldoc.perl.org/perlfork
基于wait()代码实现
use strict;
use warnings;
use 5.010;
say "Process ID: $$";
my $n = 3;
my $forks = 0;
for (1 .. $n) {
my $pid = fork;
if (not defined $pid) {
warn 'Could not fork';
next;
}
if ($pid) {
$forks++;
say "In the parent process PID ($$), Child pid: $pid Num of fork child processes: $forks";
} else {
say "In the child process PID ($$)";
sleep 2;
say "Child ($$) exiting";
exit;
}
}
for (1 .. $forks) {
my $pid = wait();
say "Parent saw $pid exiting";
}
say "Parent ($$) ending";
基于waitpid()代码实现
use strict;
use warnings;
use 5.010;
say "Process ID: $$";
my $n = 3;
my $forks = 0;
for (1 .. $n) {
my $pid = fork;
if (not defined $pid) {
warn 'Could not fork';
next;
}
if ($pid) {
$forks++;
say "In the parent process PID ($$), Child pid: $pid Num of fork child processes: $forks";
} else {
say "In the child process PID ($$)";
sleep 2;
say "Child ($$) exiting";
exit;
}
}
say "Total fork tasks: $forks";
while(1) {
my $pid = waitpid(-1, WNOHANG);
if ($pid != -1) {
say "Parent saw $pid exiting";
$forks--;
}
if ($forks == 0 && $pid == -1) {
last;
}
}
say "Parent ($$) ending";