seld/signal-handler
Lightweight PHP signal handling for CLI apps. Provides a simple API to register handlers for POSIX signals, integrate with event loops, and reliably dispatch callbacks. Ideal for daemons, workers, and long-running processes that need clean shutdowns.
Start by installing the package via Composer:
composer require seld/signal-handler
The core use case is handling OS signals (e.g., SIGINT, SIGTERM) in CLI scripts to enable graceful shutdown — especially useful for long-running workers, daemons, or console commands. Create a handler with SignalHandler::create(), register callbacks for signals, and keep the returned instance alive (critical on PHP 8.0+). For example:
use Seld\Signal\SignalHandler;
$handler = SignalHandler::create();
$handler->register(SIGINT, fn() => $this->shutdown());
$handler->register(SIGTERM, fn() => $this->shutdown());
while ($job = $this->fetchJob()) {
$this->process($job);
}
Note: Signal handling silently fails on Windows (except SIGINT/SIGTERM on PHP 7.4+), making it safe for cross-platform code.
Command::execute() to handle Ctrl+C during extended runs, preventing orphaned processes or corrupted state.exitWithLastSignal() after signal handling to ensure the process exits with the signal number (e.g., exit(SignalHandler::SIGNAL_SIGTERM) → exit code 143), which is picked up by process supervisors.SignalHandler as a service in Laravel console commands or workers, instantiated once per process. Avoid creating/disposing repeatedly during request lifecycle.SignalHandler instance in a persistent variable (e.g., class property or top-level variable). If it falls out of scope, the weak reference is GC’d and handlers never fire. Common pitfall: creating it inside a method without assigning to $this->signalHandler.declare(ticks=1); from your code (it was required in older versions).SIGINT and SIGTERM work on Windows (PHP 7.4+), and only in CLI. GUI mode or older PHP versions cause silent no-ops — ideal for "best-effort" signal handling across platforms.unregister() is destructive — Calling it clears all signals for that handler instance (no arguments needed since v2.0). If you need selective unregistration, store separate handler instances.phpstan), so IDE autocompletion and static analysis work reliably for SignalHandler::create().php -S or php artisan serve + separate terminal (not web requests) to verify SIGINT/SIGTERM.How can I help you explore Laravel packages today?