1. Use %SIG hash to trap control signal
You can set the values of the %SIG hash to be the functions you want to
handle the signal. After perl catches the signal, it looks in %SIG for a
key with the same name as the signal, then calls the subroutine value for
that key. The following is signal handler for INT signal [Fromperldoc -q SIG]
# as an anonymous subroutine
$SIG{INT} = sub { syswrite(STDERR, "ouch\n", 5 ) };
# or a reference to a function
$SIG{INT} = \&ouch;
# or the name of the function as a string
$SIG{INT} = "ouch";
sub ouch {
die "Caught a signal: $!";
}
We can define handlers for other signals as well.
$SIG{TERM} = sub { print STDERR, "Going to terminate."; };
$SIG{__DIE__} = sub { die "Going to die:".shift; };
$SIG{__WARN__} = sub { die "Going to die:".shift; };
The key of %SIG hash can be INT, ‘INT’, and __INT__.
signal handler also can be defined with eval, such as
eval {
local $SIG{ALRM} = sub { die "timeout\n" };
};
No comments :
Post a Comment