Skip to content

Commit bd2caed

Browse files
[Console] Add support for managing exit code while handling signals
1 parent 14303fc commit bd2caed

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

components/console/events.rst

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -178,16 +178,36 @@ Listeners receive a
178178
// gets the signal number
179179
$signal = $event->getHandlingSignal();
180180

181+
// sets the exit code
182+
$event->setExitCode(0);
183+
181184
if (\SIGINT === $signal) {
182185
echo "bye bye!";
183186
}
184187
});
185188

189+
It is also possible to abort the exit if you want the command to continue its
190+
execution even after the event has been dispatched, thanks to the
191+
:method:`Symfony\\Component\\Console\\Event\\ConsoleSignalEvent::abortExit`
192+
method::
193+
194+
use Symfony\Component\Console\ConsoleEvents;
195+
use Symfony\Component\Console\Event\ConsoleSignalEvent;
196+
197+
$dispatcher->addListener(ConsoleEvents::SIGNAL, function (ConsoleSignalEvent $event) {
198+
$event->abortExit();
199+
});
200+
186201
.. tip::
187202

188203
All the available signals (``SIGINT``, ``SIGQUIT``, etc.) are defined as
189204
`constants of the PCNTL PHP extension`_.
190205

206+
.. versionadded:: 6.3
207+
208+
The ``setExitCode()``, ``getExitCode()`` and ``abortExit()`` methods were introduced
209+
in Symfony 6.3.
210+
191211
If you use the Console component inside a Symfony application, commands can
192212
handle signals themselves. To do so, implement the
193213
:class:`Symfony\\Component\\Console\\Command\\SignalableCommandInterface` and subscribe to one or more signals::
@@ -208,13 +228,17 @@ handle signals themselves. To do so, implement the
208228
return [\SIGINT, \SIGTERM];
209229
}
210230

211-
public function handleSignal(int $signal): void
231+
public function handleSignal(int $signal): int|false
212232
{
213233
if (\SIGINT === $signal) {
214234
// ...
215235
}
216236

217237
// ...
238+
239+
// return an integer to set the exit code, or
240+
// false to continue normal execution
241+
return 0;
218242
}
219243
}
220244

@@ -228,6 +252,10 @@ handle all signals e.g. to do some tasks before terminating the command.
228252
``SIGUSR2``) would terminate the script by calling ``exit(0)``. Starting
229253
from Symfony 6.3, no more signal is automatically calling ``exit(0)``.
230254

255+
.. deprecated:: 6.3
256+
257+
Not returning a value in ``handleSignal()`` is deprecated since Symfony 6.3.
258+
231259
.. _`reserved exit codes`: https://www.tldp.org/LDP/abs/html/exitcodes.html
232260
.. _`Signals`: https://en.wikipedia.org/wiki/Signal_(IPC)
233261
.. _`constants of the PCNTL PHP extension`: https://www.php.net/manual/en/pcntl.constants.php

0 commit comments

Comments
 (0)