I have a PHP script (executed via php script.php
) which must be able to handle graceful shutdowns when receiving a SIGTERM
signal.
For that I want to use pcntl_signal
. Some experimentation showed me that pcntl_signal_dispatch
must be used to ensure signal handlers will actually handle any pending OS signals.
What is confusing to me:
- The documentation for
pcntl_signal
does not mention any usage ofpcntl_signal_dispatch
by any means. - The documentation for
pcntl_signal_dispatch
simply states that it will signal handlers. - My local testing always required me to call
pcntl_signal_dispatch
, otherwise my signal handlers were never picked up.
Is the usage of pcntl_signal_dispatch
mandatory for signal handlers to be called? Or are there scenarios where signal handlers are automatically called by the PHP runtime?
This is the minimal reproducable example for what I am describing:
<?php
declare(strict_types=1);
function handleSignal(int $signo): void
{
echo "Got signal: $signo\n";
}
pcntl_signal(SIGINT, 'handleSignal');
pcntl_signal(SIGTERM, 'handleSignal');
while (true) {
// Assume that this program will receive a SIGTERM signal,
// Locally you can simply do that via using htop to kill the process.
sleep(1);
// Remove this line an the script will not get any signals:
pcntl_signal_dispatch();
}