gpt4 book ai didi

perl - 等待子进程超时

转载 作者:行者123 更新时间:2023-12-02 04:27:51 31 4
gpt4 key购买 nike

我想等待两个进程(或更多)完成,或者等待计时器倒计时。计时器倒计时将在终端窗口中输出。例如:

use warnings;
use strict;
use feature qw(say);

my $pid1 = fork();
if ( $pid1 == 0 ) {
runTask1();
exit 0;
}

my $pid2 = fork();
if ( $pid2 == 0 ) {
runTask2();
exit 0;
}

my $timer = startTimer();

say "Waiting for child processes..";
my $counter = 20;
my $i = 0;
while (1) {
my $pid = wait;
last if ( $pid == -1 );
if ( $pid == $timer ) {
$counter--;
say $counter;
$timer = startTimer();
} else {
say "Child with PID=$pid finished..";
$i++;
last if $i == 2;
}
}

say "Done.";

sub startTimer {

my $pidTimer = fork();
if ( $pidTimer == 0 ) {
sleep 1;
exit 0;
}
return $pidTimer;
}

sub runTask1 {
sleep 10;
exit 0;
}

sub runTask2 {
sleep 5;
exit 0;
}

我对这种方法的担忧是我为计时器创建了一个 fork 的子进程,这看起来有点矫枉过正。这是必要的还是有更简单的方法?

最佳答案

看看alarm() - 在指定的超时后触发终止信号ALRM。这要么会终止进程,要么您可以使用:

    $SIG{'ALRM'} = \&some_sub_to_handle_alarms;

alarm() 不会传播到 fork 进程,因此您可以将其设置在“父进程”上,这样它就会在等待子进程时超时。

你可能不需要 fork 你的 pidTimer - 你可以让你的主进程处于循环中。

以下演示:

use strict;
use warnings;
use feature qw(say);

my $pid1 = fork();
if ( $pid1 == 0 ) { # Simulated Task 1
sleep 10;
exit 0;
}

my $pid2 = fork();
if ( $pid2 == 0 ) { # Simulated Task 2
sleep 5;
exit 0;
}

say "Waiting for child processes..";
my $counter = 20;
local $SIG{ALRM} = sub {
say --$counter;
alarm 1;
};
alarm 1;

while ((my $pid = wait) != -1) {
say "Child with PID=$pid finished..";
}

alarm 0;
say "Done.";

输出:

Waiting for child processes..
19
18
17
16
Child with PID=55240 finished..
15
14
13
12
11
Child with PID=55239 finished..
Done.

关于perl - 等待子进程超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25566406/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com