Whenever a signal is received, the Spatie\SignalAwareCommand\Events\SignalReceived event is dispatched.
Requirements:
- The command must define the
$handlesSignals property to include the signal you want to listen for. - You can then use Laravel's
Event::listen to catch the event.
Inside the listener, you can access the signal number via $event->signal and the command instance via $event->command. You can also use Spatie\SignalAwareCommand\Signals::getSignalName($signalNumber) to get a human-readable name for the signal.
use Spatie\SignalAwareCommand\SignalAwareCommand;
use Spatie\SignalAwareCommand\Events\SignalReceived;
use Spatie\SignalAwareCommand\Signals;
use Illuminate\Support\Facades\Event;
class YourCommand extends SignalAwareCommand
{
protected $signature = 'your-command';
protected $handlesSignals = [SIGINT];
public function handle()
{
Event::listen(function (SignalReceived $event) {
$signalNumber = $event->signal;
$signalName = Signals::getSignalName($signalNumber);
$event->command->info("Received the {$signalName} signal");
});
sleep(100);
}
}