php - Execute code after script abort on CLI -


i try execute final code after script got aborted in php. let's have php script:

while(true) {     echo 'loop';     sleep(1); } 

if execute script $ php script.php run's till given execution time.

now execute final code after script has been aborted. if i

  • hit ctrl+c
  • the execution time over

is there possibility clean in cases?

i tried pcntl_signal no luck. register_shutdown_function called if script ends successfully.

update

i found out (thx rch's link) somehow can "catch" events with:

pcntl_signal(sigterm, $restartmyself); // kill pcntl_signal(sighup,  $restartmyself); // kill -s hup or kill -1 pcntl_signal(sigint,  $restartmyself); // ctrl-c 

but if extend code with

$cleanup = function() {     echo 'clean up';     exit; };  pcntl_signal(sigint, $cleanup); 

the script keeps executing not respect code in $cleanup closure if hit ctrl+c.

the function pcntl_signal() answer situation when script interrupted using ctrl-c (and other signals). have pay attention documentation. says:

you must use declare() statement specify locations in program callbacks allowed occur signal handler function properly.

the declare() statement, amongst other things, installs callback function handles dispatching of signals received since last call, calling function pcntl_signal_dispatch() in turn calls signal handlers installed.

alternatively, can call function pcntl_signal_dispatch() when consider it's appropriate flow of code (and don't use declare(ticks=1) @ all).

this example program uses declare(ticks=1):

declare(ticks=1);  // install signal handlers pcntl_signal(sighup,  'handlesighup'); pcntl_signal(sigint,  'handlesigint'); pcntl_signal(sigterm, 'handlesigterm');   while(true) {     echo 'loop';     sleep(1); }  // reset signal handlers pcntl_signal(sighup,  sig_dfl); pcntl_signal(sigint,  sig_dfl); pcntl_signal(sigterm, sig_dfl);    /**  * sighup: controlling pseudo or virtual terminal has been closed  */ function handlesighup() {     echo("caught sighup, terminating.\n");     exit(1); }  /**  * sigint: user wishes interrupt process; typically initiated pressing control-c  *  * should noted sigint identical sigterm.  */ function handlesigint() {     echo("caught sigint, terminating.\n");     exit(1); }  /**  * sigterm: request process termination  *  * sigterm signal generic signal used cause program termination.  * normal way politely ask program terminate.  * shell command kill generates sigterm default.  */ function handlesigterm() {     echo("caught sigterm, terminating.\n");     exit(1); } 

Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -