Signals and graceful shutdown
suggest changeLong-running PHP CLI programs (queue workers, daemons, socket servers, cron jobs) get stopped from the outside: someone presses Ctrl+C, systemd or Supervisor restarts the service, docker stop or Kubernetes replaces the container. All of them tell the process to stop by sending a Unix signal.
If the script doesn't handle the signal, the kernel ends the process immediately. A job is left half done, a temp file or lock file stays behind, a database transaction gets rolled back by the server. Graceful shutdown means catching the signal, finishing (or cleanly abandoning) the current unit of work, releasing resources and exiting with a meaningful exit code.
In PHP this is done with the pcntl extension. It is only available on Unix-like systems (Linux, macOS, WSL) and only in the CLI (and CGI) SAPI. Check that it is loaded:
$ php -m | grep -E 'pcntl|posix'
pcntl
posix
Official Docker php:*-cli images don't enable it by default; add RUN docker-php-ext-install pcntl to the Dockerfile.
Signals you need to know
| Signal | Number | Sent by | Default action |
|---|---|---|---|
SIGINT |
2 | Ctrl+C in a terminal | terminate |
SIGTERM |
15 | kill <pid>, systemctl stop, docker stop, Kubernetes |
terminate |
SIGHUP |
1 | terminal closed; by convention "reload config" for daemons | terminate |
SIGQUIT |
3 | Ctrl+\ | terminate + core dump |
SIGUSR1, SIGUSR2 |
10, 12 | your own tools (kill -USR1 <pid>) |
terminate |
SIGALRM |
14 | timer set with pcntl_alarm() |
terminate |
SIGCHLD |
17 | a child process exited | ignore |
SIGKILL |
9 | kill -9, after a stop timeout |
terminate, cannot be caught |
(The numbers are for Linux on x86 and ARM. Always use the PHP constants such as SIGTERM, not the numbers.)
Service managers send SIGTERM first and wait for the process to exit. If it is still running after a grace period they send SIGKILL, which can't be caught or ignored. The grace period is 10 seconds for docker stop, 30 seconds by default in Kubernetes (terminationGracePeriodSeconds) and 90 seconds for systemd (TimeoutStopSec). Your shutdown has to fit inside that window.
What happens without a handler
This script holds a lock file, cleans up in a destructor, and has a finally block and a shutdown function:
<?php
register_shutdown_function(fn() => print("shutdown function\n"));
class TempFile {
public function __construct(public string $path) { touch($path); }
public function __destruct() { unlink($this->path); echo "removed {$this->path}\n"; }
}
$tmp = new TempFile('/tmp/job.lock');
try {
echo "working, pid ", getmypid(), "\n";
sleep(30);
} finally {
echo "finally\n";
}
Send it SIGTERM while it sleeps:
$ php nohandler.php & pid=$!
$ kill -TERM $pid; wait $pid; echo "exit code: $?"
working, pid 610
exit code: 143
$ ls /tmp/job.lock
/tmp/job.lock
None of the cleanup code ran: no finally, no destructor, no shutdown function. The kernel killed the process, and the shell reports exit code 143, which is 128 + 15 (SIGTERM). The stale lock file will block the next run.
Catching signals with pcntl_signal()
pcntl_signal(int $signal, callable|int $handler, bool $restart_syscalls = true) installs a handler. Enable asynchronous signal handling with pcntl_async_signals(true) so handlers run as soon as a signal arrives.
The standard pattern is to have the handler only set a flag, and let the main loop check the flag between units of work:
<?php
pcntl_async_signals(true);
$running = true;
$stop = function (int $signo) use (&$running): void {
echo "\ngot ", ($signo === SIGTERM ? "SIGTERM" : "SIGINT"), ", finishing current job\n";
$running = false;
};
pcntl_signal(SIGTERM, $stop);
pcntl_signal(SIGINT, $stop);
register_shutdown_function(fn() => print("shutdown function\n"));
$job = 0;
while ($running) {
$job++;
echo "job $job start\n";
usleep(300_000); // simulate work
echo "job $job done\n";
}
echo "clean exit\n";
exit(0);
Output after kill -TERM (Ctrl+C behaves the same way):
job 1 start
job 1 done
job 2 start
job 2 done
job 3 start
got SIGTERM, finishing current job
job 3 done
clean exit
shutdown function
exit code: 0
Job 3 was allowed to finish, then the loop ended and the process exited normally with code 0.
Why only set a flag? The handler runs in the middle of whatever code was executing: between two writes to a file, in the middle of building an array, while a database query is in flight. Doing real work there is risky. Setting a flag and returning is always safe.
The second argument can also be SIG_IGN (ignore the signal) or SIG_DFL (restore the default action).
The handler receives signal info
The handler gets a second argument with details about the signal, including the PID and user ID of the sender, which is handy for logging who stopped a service:
<?php
pcntl_async_signals(true);
pcntl_signal(SIGUSR1, function (int $signo, mixed $info): void {
echo "handler: signo={$info['signo']} pid={$info['pid']} uid={$info['uid']} code={$info['code']}\n";
});
$left = sleep(10);
echo "sleep returned $left\n";
Output when a shell with PID 689 runs kill -USR1:
handler: signo=10 pid=689 uid=1000 code=0
sleep returned 9
Signals interrupt sleeping and waiting
The example above shows something important: a signal wakes the process from sleep(). sleep() returns the number of seconds that were left (9 here) and time_nanosleep() returns an array with the remaining time. usleep() returns nothing but also returns early.
That's what you want for an idle worker. A loop that does sleep(5) when there's no work still reacts to SIGTERM immediately instead of up to 5 seconds later.
It also means that a sleep() or usleep() that must last the whole time has to be done in a loop. The worker example below does this.
stream_select() is interrupted too. It returns false and emits a warning, which you should handle as "check the flags and loop again", not as an error:
<?php
pcntl_async_signals(true);
$stop = false;
pcntl_signal(SIGTERM, function () use (&$stop): void { $stop = true; });
$server = stream_socket_server('tcp://127.0.0.1:8099');
while (!$stop) {
$read = [$server];
$write = $except = null;
$n = @stream_select($read, $write, $except, 30);
if ($n === false) {
echo "stream_select interrupted: ", error_get_last()['message'] ?? '', "\n";
continue;
}
if ($n > 0) {
$conn = stream_socket_accept($server);
fwrite($conn, "hello\n");
fclose($conn);
}
}
fclose($server);
echo "server stopped\n";
Output after kill -TERM:
stream_select interrupted: stream_select(): Unable to select [4]: Interrupted system call (max_fd=4)
server stopped
restart_syscalls and blocking calls
By default ($restart_syscalls = true) the signal handler is installed with the SA_RESTART flag. Some blocking system calls are then silently restarted by the kernel after a signal, and since async handlers only run when control returns to the PHP engine, the handler doesn't run until the call finishes on its own. pcntl_wait() / pcntl_waitpid() are the classic case: a parent blocked in pcntl_wait() never sees its SIGTERM handler run.
Pass false as the third argument when your code blocks in such calls. Then the call returns early (pcntl_wait() returns -1) and the handler runs. The supervisor example below needs this.
Asynchronous vs. dispatched signals
Without pcntl_async_signals(true), PHP doesn't run handlers on its own. Signals that arrive are queued, and handlers run only when you call pcntl_signal_dispatch():
<?php
// No pcntl_async_signals(): signals are queued until we dispatch them.
$stop = false;
pcntl_signal(SIGTERM, function () use (&$stop): void {
echo "handler runs\n";
$stop = true;
});
for ($i = 1; !$stop; $i++) {
echo "step $i\n";
usleep(400_000);
echo "dispatching\n";
pcntl_signal_dispatch(); // handlers for pending signals run here
}
echo "stopped after step ", $i - 1, "\n";
Output when SIGTERM arrives during step 2:
step 1
dispatching
step 2
dispatching
handler runs
stopped after step 2
exit code: 0
This gives you full control over where handlers run, at the cost of having to call pcntl_signal_dispatch() often enough. Async signals (PHP 7.1+) are simpler and are what you should use in new code. Very old code uses declare(ticks=1); for the same purpose; it is slow and has been superseded by pcntl_async_signals().
Exiting from a handler: exit() vs. exceptions
Calling exit() inside a handler stops the script right away. Shutdown functions and destructors run, but finally blocks don't:
<?php
pcntl_async_signals(true);
pcntl_signal(SIGTERM, function (): void {
echo "handler: calling exit\n";
exit(1);
});
register_shutdown_function(fn() => print("shutdown function\n"));
class Res { function __destruct() { echo "destructor\n"; } }
$r = new Res();
try {
sleep(10);
} finally {
echo "finally\n";
}
Output:
handler: calling exit
shutdown function
destructor
exit code: 1
If the code being interrupted relies on finally (releasing a lock, rolling back a transaction), throw an exception from the handler instead. It unwinds the stack from wherever the script was executing, like any other exception:
<?php
final class ShutdownRequested extends RuntimeException {}
pcntl_async_signals(true);
pcntl_signal(SIGTERM, function (): void {
throw new ShutdownRequested('SIGTERM');
});
$lock = fopen('/tmp/job.lock', 'c');
flock($lock, LOCK_EX);
try {
echo "working\n";
sleep(30);
} catch (ShutdownRequested $e) {
echo "interrupted by {$e->getMessage()}\n";
} finally {
flock($lock, LOCK_UN);
echo "lock released\n";
}
Output:
working
interrupted by SIGTERM
lock released
exit code: 0
The exception can be thrown at any line, so use this only around code that is safe to abandon at any point. The flag approach, where the code decides when to stop, is still the safer default. See try, finally, and cleanup for more on finally, and Cancellation and timeouts for using SIGALRM this way to time out a piece of code.
A complete worker
A production worker usually handles several signals:
SIGTERM/SIGINT: finish the current job, then exit.- A second
SIGINT: the user pressed Ctrl+C twice and doesn't want to wait, so exit now. - A shutdown deadline: if the current job takes longer than allowed, exit anyway before the service manager sends
SIGKILL.pcntl_alarm()schedules aSIGALRMfor this. SIGHUP: reload configuration without restarting.SIGUSR1: log status.
<?php
declare(strict_types=1);
final class Worker
{
private bool $stopping = false;
private int $processed = 0;
private array $config;
public function __construct(private string $configFile)
{
$this->config = $this->loadConfig();
}
public function installSignalHandlers(): void
{
pcntl_async_signals(true);
pcntl_signal(SIGTERM, $this->onStop(...));
pcntl_signal(SIGINT, $this->onStop(...));
pcntl_signal(SIGHUP, fn() => $this->config = $this->loadConfig());
pcntl_signal(SIGUSR1, fn() => $this->log("status: processed={$this->processed}"));
pcntl_signal(SIGALRM, function (): void {
$this->log('shutdown deadline exceeded, exiting now');
exit(1);
});
}
private function onStop(int $signo): void
{
if ($this->stopping) {
$this->log('second stop signal, exiting immediately');
exit(1);
}
$this->stopping = true;
$this->log('stop requested, finishing current job');
pcntl_alarm($this->config['shutdown_timeout']); // hard deadline
}
public function run(): int
{
$this->log('started, pid ' . getmypid());
while (!$this->stopping) {
$job = $this->nextJob();
if ($job === null) {
sleep(5); // idle: a signal wakes us up early
continue;
}
$this->handle($job);
}
$this->log("stopped cleanly after {$this->processed} jobs");
return 0;
}
private function nextJob(): ?int
{
return $this->processed < 1000 ? $this->processed + 1 : null;
}
private function handle(int $job): void
{
$remaining = $this->config['job_ms'] * 1000;
while ($remaining > 0) {
// usleep() can be cut short by a signal, so sleep in a loop
// until the simulated work is really done.
$start = hrtime(true);
usleep($remaining);
$remaining -= intdiv(hrtime(true) - $start, 1000);
}
$this->processed++;
}
private function loadConfig(): array
{
$config = json_decode(file_get_contents($this->configFile), true, flags: JSON_THROW_ON_ERROR);
$this->log('config loaded: ' . json_encode($config));
return $config;
}
private function log(string $msg): void
{
fwrite(STDERR, date('H:i:s') . " [worker] $msg\n");
}
}
$worker = new Worker(__DIR__ . '/worker.json');
$worker->installSignalHandlers();
exit($worker->run());
$this->onStop(...) is first-class callable syntax; it turns a private method into a closure that pcntl_signal() can call.
Drive it from another shell:
echo '{"job_ms": 400, "shutdown_timeout": 10}' > worker.json
php worker.php & pid=$!
sleep 1
kill -USR1 $pid; sleep 0.2
echo '{"job_ms": 200, "shutdown_timeout": 10}' > worker.json
kill -HUP $pid; sleep 1
kill -USR1 $pid; sleep 0.1
kill -TERM $pid; wait $pid; echo "exit code: $?"
Output:
18:35:31 [worker] config loaded: {"job_ms":400,"shutdown_timeout":10}
18:35:31 [worker] started, pid 617
18:35:32 [worker] status: processed=2
18:35:32 [worker] config loaded: {"job_ms":200,"shutdown_timeout":10}
18:35:33 [worker] status: processed=7
18:35:33 [worker] stop requested, finishing current job
18:35:34 [worker] stopped cleanly after 9 jobs
exit code: 0
With jobs that take 5 seconds and "shutdown_timeout": 2, the deadline kicks in:
18:35:43 [worker] config loaded: {"job_ms":5000,"shutdown_timeout":2}
18:35:43 [worker] started, pid 653
18:35:44 [worker] stop requested, finishing current job
18:35:46 [worker] shutdown deadline exceeded, exiting now
exit code: 1
And pressing Ctrl+C twice (two SIGINTs) exits right away:
18:35:46 [worker] config loaded: {"job_ms":5000,"shutdown_timeout":2}
18:35:46 [worker] started, pid 678
18:35:46 [worker] stop requested, finishing current job
18:35:47 [worker] second stop signal, exiting immediately
exit code: 1
Pick a shutdown timeout a few seconds shorter than the grace period of whatever runs the worker, so your own cleanup gets to run before SIGKILL arrives. If jobs can take longer than that, make them resumable or idempotent (use a queue that redelivers unacknowledged messages), because some of them will be cut short.
Protecting a critical section with pcntl_sigprocmask()
Sometimes a few lines must never be interrupted, for example writing a state file and renaming it into place. pcntl_sigprocmask() blocks signals temporarily. A blocked signal is not lost: it stays pending and is delivered as soon as you unblock it.
<?php
pcntl_async_signals(true);
pcntl_signal(SIGTERM, function (): void {
echo "SIGTERM handled\n";
exit(0);
});
function writeAtomically(string $file, string $data): void
{
// Block SIGTERM and SIGINT while the critical section runs.
pcntl_sigprocmask(SIG_BLOCK, [SIGTERM, SIGINT], $old);
try {
$tmp = "$file.tmp";
file_put_contents($tmp, $data);
sleep(1); // a signal arriving now stays pending
rename($tmp, $file);
echo "state saved\n";
} finally {
// Restore the old mask; pending signals are delivered here.
pcntl_sigprocmask(SIG_SETMASK, $old);
}
}
writeAtomically('/tmp/state.json', '{"cursor": 42}');
echo "not reached\n";
Output when SIGTERM is sent 0.3 seconds in:
state saved
SIGTERM handled
exit code: 0
The signal arrived during sleep(1) but the handler ran only after the state file was complete.
Waiting for signals synchronously
A process that mostly waits (a scheduler that wakes up every few seconds, a simple daemon) can skip handlers entirely. Block the signals so they are queued, then wait for them with pcntl_sigtimedwait() (with a timeout) or pcntl_sigwaitinfo() (forever):
<?php
// Block the signals: they are queued instead of running a handler
// or killing the process, and we pick them up when we are ready.
$signals = [SIGTERM, SIGINT, SIGHUP];
pcntl_sigprocmask(SIG_BLOCK, $signals);
echo "pid ", getmypid(), ", waiting\n";
while (true) {
$signo = pcntl_sigtimedwait($signals, $info, 2); // wait up to 2 seconds
if ($signo === false) {
echo "timeout, doing periodic work\n";
continue;
}
if ($signo === SIGHUP) {
echo "SIGHUP: reloading\n";
continue;
}
echo "signal $signo: stopping\n";
break;
}
echo "bye\n";
Output with SIGHUP sent after 2.5 seconds and SIGTERM after 3:
pid 1140, waiting
timeout, doing periodic work
SIGHUP: reloading
signal 15: stopping
bye
The code runs straight through with no shared flags and nothing interrupting it mid-statement.
Exit codes after a signal
Shells, systemd and CI systems tell "exited normally" apart from "killed by a signal". A process killed by signal N is reported as exit code 128 + N: 130 for SIGINT, 143 for SIGTERM.
When your script handles the signal and then calls exit(0), it looks like it finished successfully. That's usually right for a worker that was asked to stop. For a command-line tool interrupted by Ctrl+C, the convention is to report the interruption, so that a calling shell script stops too. Do the cleanup, restore the default action and send the signal to yourself:
<?php
pcntl_async_signals(true);
$received = 0;
$handler = function (int $signo) use (&$received): void {
$received = $signo;
};
pcntl_signal(SIGINT, $handler);
pcntl_signal(SIGTERM, $handler);
while ($received === 0) {
sleep(1);
}
echo "cleaning up\n";
// Restore the default action and send the signal to ourselves, so the
// parent (shell, systemd, supervisor) sees "killed by SIGINT/SIGTERM".
pcntl_signal($received, SIG_DFL);
posix_kill(getmypid(), $received);
Output after Ctrl+C (SIGINT):
cleaning up
exit code: 130
See Return Codes for exit codes in general.
Stopping child processes
A parent that forks workers has to pass the stop request on to them and wait until they exit. Otherwise children keep running, or turn into zombies, after the parent is gone. (A terminal's Ctrl+C reaches the whole foreground process group, but kill and docker stop signal only one process.)
<?php
pcntl_async_signals(true);
$children = [];
for ($i = 1; $i <= 3; $i++) {
$pid = pcntl_fork();
if ($pid === -1) {
exit("fork failed\n");
}
if ($pid === 0) {
// Child: its own graceful-stop handler.
$stop = false;
pcntl_signal(SIGTERM, function () use (&$stop): void { $stop = true; });
while (!$stop) {
usleep(100_000);
}
echo "child $i stopped\n";
exit(0);
}
$children[$pid] = $i;
}
echo "started ", count($children), " children\n";
$forward = function (int $signo) use (&$children): void {
foreach (array_keys($children) as $pid) {
posix_kill($pid, SIGTERM);
}
};
pcntl_signal(SIGTERM, $forward, false);
pcntl_signal(SIGINT, $forward, false);
// Reap children until all are gone.
while ($children) {
$pid = pcntl_wait($status); // blocks; returns -1 if interrupted by a signal
if ($pid > 0) {
$code = pcntl_wifexited($status) ? pcntl_wexitstatus($status) : -1;
echo "reaped child {$children[$pid]}, exit code $code\n";
unset($children[$pid]);
}
}
echo "supervisor done\n";
Output after kill -TERM <parent pid>:
started 3 children
child 1 stopped
child 2 stopped
child 3 stopped
reaped child 1, exit code 0
reaped child 3, exit code 0
reaped child 2, exit code 0
supervisor done
exit code: 0
Two details matter here:
- The handlers are installed with
$restart_syscalls = false. With the defaulttruethe parent stays blocked inpcntl_wait()forever, the handler never runs and the children are never told to stop. - The parent installs its handler after forking. Children inherit signal handlers installed before
pcntl_fork(), which is rarely what you want.
For processes started with proc_open(), use proc_terminate($process, SIGTERM) and then proc_close(). See Creating child process using fork and Spawning non-blocking processes with proc_open.
Docker and PID 1
In a container the main process runs as PID 1, and the kernel treats PID 1 specially: signals whose action is the default (terminate) are ignored. A PHP script without a SIGTERM handler doesn't stop on docker stop; Docker waits the full 10 seconds and then sends SIGKILL.
You can see this on Linux without Docker by starting PHP in a new PID namespace:
$ unshare --pid --fork --map-root-user --mount-proc \
php -r 'echo "pid in namespace: ", getmypid(), "\n"; sleep(3); echo "still alive after SIGTERM\n";' &
$ kill -TERM <pid of php>
pid in namespace: 1
still alive after SIGTERM
With a handler installed, the same SIGTERM is delivered normally.
Container checklist:
- Use the exec form
CMD ["php", "worker.php"]. The shell formCMD php worker.phpruns/bin/sh -c, the shell becomes PID 1 and doesn't forwardSIGTERMto PHP. - If a wrapper script starts PHP, end it with
exec php worker.phpso PHP replaces the shell. - Install a
SIGTERMhandler, or run withdocker run --init(or tini) so a tiny init process becomes PID 1, forwards signals and reaps zombies. - Set
STOPSIGNALin the Dockerfile if your program expects a different signal, and raisedocker stop -t/terminationGracePeriodSecondsif jobs need more time.
Web requests and PHP-FPM
pcntl is not available under PHP-FPM, Apache mod_php or other web SAPIs, and you shouldn't install signal handlers in web code. The FPM master process manages signals for its workers: SIGQUIT makes FPM stop gracefully (workers finish their current request, bounded by process_control_timeout), SIGTERM and SIGINT stop it immediately, and SIGUSR2 reloads it gracefully. Set process_control_timeout in php-fpm.conf, because with the default of 0 workers are not waited for.
In a request, what you can detect is the client going away: see ignore_user_abort() and connection_aborted().
Windows
pcntl doesn't exist on Windows. For console programs PHP 7.4+ provides sapi_windows_set_ctrl_handler(), which catches Ctrl+C and Ctrl+Break:
<?php
// Windows only: Ctrl+C / Ctrl+Break handling in the console.
$stop = false;
sapi_windows_set_ctrl_handler(function (int $event) use (&$stop): void {
echo $event === PHP_WINDOWS_EVENT_CTRL_C ? "Ctrl+C\n" : "Ctrl+Break\n";
$stop = true;
});
while (!$stop) {
usleep(100_000);
}
echo "clean exit\n";
Cross-platform code can check function_exists('pcntl_signal') and function_exists('sapi_windows_set_ctrl_handler') and install whichever is available.
Checklist
- Call
pcntl_async_signals(true)and handle at leastSIGTERMandSIGINTin every long-running CLI script. - In handlers, set a flag; check it in the main loop between units of work.
- Use
exit()in a handler only when skippingfinallyblocks is acceptable; throw an exception if they must run. - Remember that signals cut
sleep(),usleep()andstream_select()short; loop if you need the full duration. - Pass
falsefor$restart_syscallswhen the process blocks inpcntl_wait(). - Enforce your own shutdown deadline with
pcntl_alarm(), shorter than the service manager's grace period. - Block signals with
pcntl_sigprocmask()around short critical sections. - Forward stop signals to child processes and reap them before exiting.
- In containers use the exec form of
CMD, or--init, so the signal reaches PHP. SIGKILLcan't be handled; design jobs to be safely retried.