New in Symfony 5.2: Console signals
October 13, 2020 • Published by Javier Eguiluz
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
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
// ...
use Symfony\Component\Console\Command\SignalableCommandInterface;
class SignalCommand extends Command implements SignalableCommandInterface
{
// ...
protected function execute(InputInterface $input, OutputInterface $output): int
{
// ...
}
public function getSubscribedSignals(): array
{
// return here any of the constants defined by PCNTL extension
// https://www.php.net/manual/en/pcntl.constants.php
return [SIGINT, SIGTERM];
}
public function handleSignal(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
// ...
use Symfony\Component\Console\Event\ConsoleSignalEvent;
class SignalSubscriber implements EventSubscriberInterface
{
// ...
public function handleSignal(ConsoleSignalEvent $event)
{
$signal = $event->getHandlingSignal();
// ...
}
public static function getSubscribedEvents()
{
return [
ConsoleEvents::SIGNAL => 'handleSignal',
];
}
}
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.