Contributed by
Marie
and Grégoire Pineau
in #33729
and #37827.
Signals are an inter-process communication mechanism used by console commands.
A signal is an asynchronous notification sent to a process (or to a specific
thread within the same process) in order to notify it of an event that occurred.
For example, when you press Ctrl+C
in a command, the operating system
sends the SIGINT
signal to it.
Symfony 5.2 introduces support for responding to signals in your commands
(e.g. to perform some cleanup tasks when quitting a command). If you want to
handle some signals in a command, implement the new SignalableCommandInterface
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | // ...useSymfony\Component\Console\Command\SignalableCommandInterface;classSignalCommandextendsCommandimplementsSignalableCommandInterface{// ...protectedfunctionexecute(InputInterface$input,OutputInterface$output):int{// ...}publicfunctiongetSubscribedSignals():array{// return here any of the constants defined by PCNTL extension// https://www.php.net/manual/en/pcntl.constants.phpreturn[SIGINT,SIGTERM];}publicfunctionhandleSignal(int$signal){if(SIGINT===$signal){// ...}// ...}} |
If you prefer to handle some signals for all application commands (e.g. to log
or profile commands), define an event listener or subscriber and listen to
the new ConsoleEvents::SIGNAL
event:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | // ...useSymfony\Component\Console\Event\ConsoleSignalEvent;classSignalSubscriberimplementsEventSubscriberInterface{// ...publicfunctionhandleSignal(ConsoleSignalEvent$event){$signal=$event->getHandlingSignal();// ...}publicstaticfunctiongetSubscribedEvents(){return[ConsoleEvents::SIGNAL=>'handleSignal',];}} |