If you have a script that needs certain sections to not be interrupted by a signal (especially SIGTERM or SIGINT), but want to make your script ready to process that signal ASAP, there's only one way to do it. Flag the script as having received the signal, and wait for your script to say its ready to process it.
Here's a sample script:
$allow_exit = true; // are we permitting exit?
$force_exit = false; // do we need to exit?
declare(ticks = 1);
register_tick_function('check_exit');
pcntl_signal(SIGTERM, 'sig_handler');
pcntl_signal(SIGINT, 'sig_handler');
function sig_handler () {
global $allow_exit, $force_exit;
if ($allow_exit)
exit;
else
$force_exit = true;
}
function check_exit () {
global $allow_exit, $force_exit;
if ($force_exit && $allow_exit)
exit;
}
$allow_exit = false;
$i = 0;
while (++$i) {
echo "still going (${i})\n";
if ($i == 10)
$allow_exit = true;
sleep(2);
}
?>
You set $allow_exit to true at all times when it is perfectly acceptable that your script could exit without warning. In sections where you really need the script to continue running, you set $allow_exit to false. Any signals received while $allow_exit is false will not take effect until you set $allow_exit to true.
$allow_exit = true;
// unimportant stuff here. exiting will not harm anything
$allow_exit = false;
// really important stuff not to be interrupted
$allow_exit = true;
// more unimportant stuff. if signal was received during
// important processing above, script will exit here
?>