沃梦达 / 编程问答 / php问题 / 正文

如何捕捉KILL、HUP或USER ABORT信号?

How do I catch a KILL or HUP or User Abort signal?(如何捕捉KILL、HUP或USER ABORT信号?)

本文介绍了如何捕捉KILL、HUP或USER ABORT信号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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.

这篇关于如何捕捉KILL、HUP或USER ABORT信号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何捕捉KILL、HUP或USER ABORT信号?

基础教程推荐