Capturing Termination Signals in PHP

Consider the scenario of a PHP script which can be run for a period of time, stopped, and continue its task later on. A common necessity for such a script may be to detect when the script is terminated, and perform some functions at that time.

This can be accomplished by having the script capture the termination signal (SIGTERM/SIGINT). Let us apply this to a mock script where we want to log the amount of time for which the script ran.

<?php
$time_start = microtime(true);
declare(ticks = 1);

pcntl_signal(SIGTERM, "signal_handler");
pcntl_signal(SIGINT, "signal_handler");

function signal_handler($signal) {
    global $time_start;
    switch($signal) {
        case SIGTERM:
        case SIGINT:
            file_put_contents("runtime.txt", microtime(true) - $time_start . "\n", FILE_APPEND);
            exit;
    }
}

while (1){
    usleep(100);
}

?>

Most of the above should be self-explanatory, except, perhaps the declare line. Since PHP 4.3.0, pcntl_signal uses ticks as the signal callback mechanism, necessitating that line for the code to function.

As long as you don’t terminate your script will SIGKILL, the above will work fine (e.g. if you terminate with Ctrl+C, kill, or even killall; only kill -9 will not let the script capture the signal).

By cyberx86

Just a random guy who dabbles with assorted technologies yet works in a completely unrelated field.

Leave a comment

Your email address will not be published. Required fields are marked *