我有一个脚本在我的linux服务器的后台运行,我想捕获像重启或任何会杀死这个脚本的信号,而是在实际退出之前保存任何importante信息。
我认为我需要捕获的大部分内容是SIGINT,SIGTERM,SIGHUP,SIGKILL。
如何抓住任何这些信号并让它执行退出功能,否则继续执行它正在执行的任何操作?
伪perl代码:
#!/usr/bin/perl
use stricts;
use warnings;
while (true)
{
#my happy code is running
#my happy code will sleep for a few until its breath is back to keep running.
}
#ops I have detected an evil force trying to kill me
#let's call the safe exit.
sub safe_exit()
{
# save stuff
exit(1);
}
伪php代码:
<?php
while (1)
{
#my happy code is running
#my happy code will sleep for a few until its breath is back to keep running.
}
#ops I have detected an evil force trying to kill me
#let's call the safe exit.
function safe_exit()
{
# save stuff
exit(1);
}
?>
答案 0 :(得分:17)
PHP使用pcntl_signal
来注册信号处理程序,如下所示:
declare(ticks = 1);
function sig_handler($sig) {
switch($sig) {
case SIGINT:
# one branch for signal...
}
}
pcntl_signal(SIGINT, "sig_handler");
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP, "sig_handler");
# Nothing for SIGKILL as it won't work and trying to will give you a warning.
答案 1 :(得分:5)
的Perl:
@SIG{qw( INT TERM HUP )} = \&safe_exit;
无法抓住SIGKILL。它不会被发送到该过程。
perlvar中记录了 %SIG
。另请参阅perlipc
答案 2 :(得分:1)
对于perl版本,请参阅perldoc -q signal
- 基本上,将$SIG{signal}
设置为子参考。