How do I catch a KILL or HUP or User Abort signal?

萝らか妹 提交于 2020-01-13 08:26:07

问题


I have a script running on the background of my linux server and I would like to catch signals like reboot or anything that would kill this script and instead save any importante information before actually exiting.

I think most of what I need to catch is, SIGINT, SIGTERM, SIGHUP, SIGKILL.

How do catch any of these signals and have it execute an exit function otherwise keep executing whatever it was doing ?

pseudo perl code:

#!/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);
}

pseudo php code:

<?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);
}
?>

回答1:


PHP uses pcntl_signal to register a signal handler, so something like this:

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.



回答2:


Perl:

$SIG{$_} = \&safe_exit for qw( INT TERM HUP );

SIGKILL cannot be caught. It is not sent to the process.

%SIG is documented in perlvar. See also perlipc




回答3:


For the perl version, see perldoc -q signal -- basically, set $SIG{signal} to a sub reference.



来源:https://stackoverflow.com/questions/7864349/how-do-i-catch-a-kill-or-hup-or-user-abort-signal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!