Skip to content

Commit 45f8e92

Browse files
committed
feature #18001 [Console] Add support for managing exit code while handling signals (alexandre-daubois)
This PR was merged into the 6.3 branch. Discussion ---------- [Console] Add support for managing exit code while handling signals Fixes #17997 Commits ------- c2b56fe [Console] Add support for managing exit code while handling signals
2 parents eb2a4bd + c2b56fe commit 45f8e92

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,11 +178,31 @@ 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+
201+
.. versionadded:: 6.3
202+
203+
The ``setExitCode()``, ``getExitCode()`` and ``abortExit()`` methods were introduced
204+
in Symfony 6.3.
205+
186206
.. tip::
187207

188208
All the available signals (``SIGINT``, ``SIGQUIT``, etc.) are defined as
@@ -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)