Skip to content

[Console] Add support for managing exit code while handling signals #18001

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 8, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 29 additions & 1 deletion components/console/events.rst
Original file line number Diff line number Diff line change
Expand Up @@ -178,11 +178,31 @@ Listeners receive a
// gets the signal number
$signal = $event->getHandlingSignal();

// sets the exit code
$event->setExitCode(0);

if (\SIGINT === $signal) {
echo "bye bye!";
}
});

It is also possible to abort the exit if you want the command to continue its
execution even after the event has been dispatched, thanks to the
:method:`Symfony\\Component\\Console\\Event\\ConsoleSignalEvent::abortExit`
method::

use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Event\ConsoleSignalEvent;

$dispatcher->addListener(ConsoleEvents::SIGNAL, function (ConsoleSignalEvent $event) {
$event->abortExit();
});

.. versionadded:: 6.3
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lets move the version added above the tip please

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done 🙂


The ``setExitCode()``, ``getExitCode()`` and ``abortExit()`` methods were introduced
in Symfony 6.3.

.. tip::

All the available signals (``SIGINT``, ``SIGQUIT``, etc.) are defined as
Expand All @@ -208,13 +228,17 @@ handle signals themselves. To do so, implement the
return [\SIGINT, \SIGTERM];
}

public function handleSignal(int $signal): void
public function handleSignal(int $signal): int|false
{
if (\SIGINT === $signal) {
// ...
}

// ...

// return an integer to set the exit code, or
// false to continue normal execution
return 0;
}
}

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

.. deprecated:: 6.3

Not returning a value in ``handleSignal()`` is deprecated since Symfony 6.3.

.. _`reserved exit codes`: https://www.tldp.org/LDP/abs/html/exitcodes.html
.. _`Signals`: https://en.wikipedia.org/wiki/Signal_(IPC)
.. _`constants of the PCNTL PHP extension`: https://www.php.net/manual/en/pcntl.constants.php