微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 如何捕获KILL或HUP或用户中止信号?

我有一个脚本在我的 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);
}
?>
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.

原文地址:https://www.jb51.cc/php/138248.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐