在Perl中捕捉和处理 Signals

通过 %SIG Hash

use strict;
use warnings;

$SIG{INT} = sub {die "Caught a sigint $!"};

sleep(100);

如果运行这个Perl程序,然后再按control-c,就会发送 SIGINT 给Perl程序,然后 $SIG{INT} 对应的方法会捕捉到 SIGINT 信号

通过 sigtrap 指令

sigtrap 是用来更方便的维护 %SIG 的指令

sigtrap 把信号分为3组:

  • normal-signals(HUP, PIPE, INT and TERM)

  • error-signals(ABRT, BUS, EMT, FPE, ILL, QUIT, SEGV, SYS and TRAP)

  • old-interface-signals(ABRT, BUS, EMT, FPE, ILL, PIPE, QUIT, SEGV, SYS, TERM and TRAP)

例如:

use strict;
use warnings;
use sigtrap qw/die normal-signals/;

sleep(100);


use strict;
use warnings;
use sigtrap qw/handler signal_handler normal-signals/;

sub signal_handler {
    die "Caught a signal $!";
}

sleep(100);

关于 signal

The default signal for kill is TERM

control+c will send interrupt signal(SIGINT) to program

参考:

  1. http://perltricks.com/article/37/2013/8/18/Catch-and-Handle-Signals-in-Perl/
  2. https://superuser.com/questions/107543/bash-man-page-kill-pid-vs-kill-9-pid
  3. https://metacpan.org/pod/sigtrap

Perl

这篇文章: 有用 无用
创建 2017-04-16 03:41:41 / 更新 2017-04-16 05:26:18