Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

signals

perl

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);
}
?>
like image 794
Prix Avatar asked Oct 23 '11 04:10

Prix


People also ask

Can SIGTERM be caught?

The SIGTERM signal is sent to a process to request its termination. Unlike the SIGKILL signal, it can be caught and interpreted or ignored by the process.

What signals Cannot be caught?

There are two signals which cannot be intercepted and handled: SIGKILL and SIGSTOP.

What is HUP signal?

The HUP signal is sent to a process when its controlling terminal is closed. It was originally designed to notify a serial line drop (HUP stands for "Hang Up"). In modern systems, this signal usually indicates the controlling pseudo or virtual terminal is closed.

What does kill HUP do?

a kill -HUP sends the signal "2" to the process. This tells the process to re-read its configuration but do not exit.


1 Answers

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.
like image 177
mu is too short Avatar answered Nov 10 '22 20:11

mu is too short