加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

linux – 在perl中收到任何信号时,睡眠会中断吗?

发布时间:2020-12-14 01:13:48 所属栏目:Linux 来源:网络整理
导读:我有这个简单的perl守护进程: #!/usr/bin/perluse strict;use warnings;use Proc::Daemon;Proc::Daemon::Init;my $continue = 1;$SIG{TERM} = sub { $continue = 0 };$SIG{USR1} = sub { do_process(1) };# basic daemon boxesd_log("started boxesd");whil
我有这个简单的perl守护进程:

#!/usr/bin/perl

use strict;
use warnings;
use Proc::Daemon;

Proc::Daemon::Init;

my $continue = 1;

$SIG{TERM} = sub { $continue = 0 };
$SIG{USR1} = sub { do_process(1) };

# basic daemon                                                                                    

boxesd_log("started boxesd");

while ($continue) {
    do_process(0);
    sleep(30);
}

boxesd_log("finished boxesd");

exit(0);

# required subroutines                                                                            

sub do_process {
    my ($notified) = @_;
    boxesd_log("doing it $notified");
}

但有些事情是行不通的.

守护程序启动时,它会每30秒记录一次,而不会发出预期的通知:

Sat Oct 30 21:05:47 2010 doing it 0
Sat Oct 30 21:06:17 2010 doing it 0
Sat Oct 30 21:06:47 2010 doing it 0

当我使用kill -USR1 xxxxx将USR1信号发送到进程时出现问题.输出不是我所期望的:

Sat Oct 30 21:08:25 2010 doing it 1
Sat Oct 30 21:08:25 2010 doing it 0

我得到两个连续的条目,一个来自信号处理子程序,另一个来自永远运行的循环.每当收到USR1信号时,似乎睡眠就会中断.

到底是怎么回事?

解决方法

在您的程序将处理输入信号的意义上,睡眠中断,但循环将继续(返回睡眠状态),直到收到TERM信号.这是 sleep()函数的记录行为:

May be interrupted if the process receives a signal such as “SIGALRM”.

请注意,如果您需要休眠30秒,即使被信号中断,您也可以确定睡眠的秒数,然后再次休眠:

while (1)
{
    my $actual = sleep(30);
    sleep(30 - $actual) if $actual < 30;
}

PS.您可以在perldoc perlipc中阅读有关信号处理的更多信息,并在W. Richard Stevens中阅读几乎任何unix编程手册.:)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读