Pau*_*kov 2 perl timer interrupt
让我用代码示例解释任务:
#!/usr/bin/perl
use strict;
use warnings;
my $t = 3;
eval {
local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
print "Start $t\n";
alarm(10);
sleep($t); # instead of this I have some data that collect code
alarm(0);
print "done with $t\n";
};
if ($@) {
die unless $@ eq "alarm\n";
print "timeout\n";
}
Run Code Online (Sandbox Code Playgroud)
而不是sleep我有一些代码将数据推送到数组.在x秒期间,数组将保证由所需数据填充.
问题:如何在x第二次打印数组后,不使用sleep(非阻塞方式)?
据我所知,在perl中设置计时器的最简单方法就是使用$SIG{ALRM}.但是如果我不需要定时器(不能使用sleep)该怎么办,我只需要设置一个必须在预定义的秒数后运行的中断?也许我应该用SIGINT这个任务?
任何帮助赞赏.
要创建自己的中断,需要两个执行线程.实现此目的的一种方法是启动子进程,该进程将在满足某些条件时向其父进程发出信号.
$SIG{USR1} = \&code_to_run_after_interrupt;
my $ppid = $$; # process id of parent
if (fork() == 0) {
# child process
sleep 15;
kill 'USR1', $ppid;
exit;
}
... main execution thread
Run Code Online (Sandbox Code Playgroud)
fork调用15秒后,主脚本将停止正在执行的操作,在命名的子例程中执行代码code_to_run_after_interrupt,然后恢复执行的主线程.
(我SIGUSR1在这里使用,因为处理SIGINT可能会让你无法Ctrl-C用来阻止你的程序)
| 归档时间: |
|
| 查看次数: |
236 次 |
| 最近记录: |