Home » Php » Destructors and shutdown functions when exiting by Ctrl+C in PHP-CLI

Destructors and shutdown functions when exiting by Ctrl+C in PHP-CLI

Posted by: admin February 12, 2018 Leave a comment

Questions:

If I use Ctrl+C to exit a PHP script running in CLI, neither the shutdown functions, nor the destructors of instantiated objects, nor any output buffers are handled. Instead the program just dies. Now, this is probably a good thing, since that’s what Ctrl+C is supposed to do. But is there any way to change that? Is it possible to force Ctrl+C to go through the shutdown functions?

More specifically, this is about serialising and saving data on exiting of the script, so it can be reloaded and resumed the next time the script runs. Periodically saving the data could work, but would still lose everything from the last save onward. What other options are there?

Answers:

Obviously PCNTL is *nix only, but … You can register handlers for all the individual signals for a more robust solution, but specifically to do something when a CTL+C interrupt is encountered:

<?php
declare(ticks = 1);

pcntl_signal(SIGINT, function() {
    echo "Caught SIGINT\n";
    die;
});

while (true) {
    // waiting for your CTRL+C
}

Questions:
Answers:

Take a look at PCNTL especially pcntl_signal()