PHP's register_shutdown_function to fire when a script is killed from the command line?

为君一笑 提交于 2020-01-21 06:34:06

问题


Is it possible to invoke a function when a cron process is killed from the command line (via Ctrl+c) or with the kill command?

I have tried register_shutdown_function(), but it doesn't seem to be invoked when the script is killed, but does get invoked when the script ends normally.

I am trying to log the result to a file and update a database value when a cron instance is killed automatically (ie. has been running too long).


回答1:


According to a comment in the manual on register_shutdown_function(), this can be done the following way:

When using CLI ( and perhaps command line without CLI - I didn't test it) the shutdown function doesn't get called if the process gets a SIGINT or SIGTERM. only the natural exit of PHP calls the shutdown function. To overcome the problem compile the command line interpreter with --enable-pcntl and add this code:

 <?php
 declare(ticks = 1); // enable signal handling
 function sigint()  { 
    exit;  
 }  
 pcntl_signal(SIGINT, 'sigint');  
 pcntl_signal(SIGTERM, 'sigint');  
 ?>

This way when the process recieves one of those signals, it quits normaly, and the shutdown function gets called. ... (abbreviating to save space, read the full text)

If that is too much hassle, I would consider doing the timing out from within PHP by setting a time limit instead. Reaching the limit will throw a fatal error, and the shutdown function should get called normally.



来源:https://stackoverflow.com/questions/3909798/phps-register-shutdown-function-to-fire-when-a-script-is-killed-from-the-comman

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!