Skip to content
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

[9.x] Adds documentation about Signal Traps 🚦 #8178

Merged
merged 2 commits into from
Sep 13, 2022
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
46 changes: 14 additions & 32 deletions artisan.md
Original file line number Diff line number Diff line change
Expand Up @@ -615,47 +615,29 @@ If you would like to call another console command and suppress all of its output
<a name="signal-handling"></a>
## Signal Handling

The Symfony Console component, which powers the Artisan console, allows you to indicate which process signals (if any) your command handles. For example, you may indicate that your command handles the `SIGINT` and `SIGTERM` signals.

To get started, you should implement the `Symfony\Component\Console\Command\SignalableCommandInterface` interface on your Artisan command class. This interface requires you to define two methods: `getSubscribedSignals` and `handleSignal`:

```php
<?php

use Symfony\Component\Console\Command\SignalableCommandInterface;

class StartServer extends Command implements SignalableCommandInterface
{
// ...

/**
* Get the list of signals handled by the command.
*
* @return array
*/
public function getSubscribedSignals(): array
{
return [SIGINT, SIGTERM];
}
As you may know, operating systems allow signals to be sent to running processes. For example, the `SIGTERM` signal is how operating systems ask a program to terminate. If you wish to listen for signals in your Artisan console commands and execute code when they occur, you may use the `trap` method:

/**
* Handle an incoming signal.
* Execute the console command.
*
* @param int $signal
* @return void
* @return mixed
*/
public function handleSignal(int $signal): void
public function handle()
{
if ($signal === SIGINT) {
$this->stopServer();
$this->trap(SIGTERM, fn () => $this->shouldKeepRunning = false);

return;
while ($this->shouldKeepRunning) {
// ...
}
}
}
```

As you might expect, the `getSubscribedSignals` method should return an array of the signals that your command can handle, while the `handleSignal` method receives the signal and can respond accordingly.
To listen for multiple signals at once, you may provide an array of signals to the `trap` method:

$this->trap([SIGTERM, SIGQUIT], function ($signal) {
$this->shouldKeepRunning = false;

dump($signal); // SIGTERM / SIGQUIT
});

<a name="stub-customization"></a>
## Stub Customization
Expand Down