我有一个在Linux服务器后台运行的脚本,我想捕获诸如重新启动之类的信号或任何会杀死该脚本的信号,而是在实际退出之前保存所有重要信息。
我认为我最需要了解的是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);
}
?>
最佳答案
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.
关于php - 如何捕获KILL或HUP或User Abort信号?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7864349/