Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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?

like image 563
Niet the Dark Absol Avatar asked Nov 13 '12 20:11

Niet the Dark Absol


2 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
}
like image 147
rdlowrey Avatar answered Oct 15 '22 07:10

rdlowrey


Take a look at PCNTL especially pcntl_signal()

like image 42
martinkacmar Avatar answered Oct 15 '22 07:10

martinkacmar