PHP › PHP CLI Scripting
How should a long running PHP CLI script, such as a queue worker, handle graceful shutdown when it receives a termination signal from the operating system?
AdvancedAnswer
A long running script can register signal handlers using PHP's pcntl extension to listen for signals like SIGTERM, which is typically sent by process managers or deployment tools requesting a graceful shutdown, allowing the script to finish processing its current unit of work, clean up any open resources like database connections, and exit cleanly, rather than being abruptly killed mid task, which could leave data in an inconsistent state.
pcntl_signal(SIGTERM, function () {
echo 'Shutting down gracefully...';
exit(0);
});
while (true) {
pcntl_signal_dispatch();
processNextJob();
}Real-world example A queue worker script registers a SIGTERM signal handler, ensuring that when a deployment process asks it to stop, it finishes processing its current job completely before shutting down, rather than potentially leaving a job half processed.