Skip to content

Commit

Permalink
[9.x] Adds documentation about Signal Traps 🚦 (#8178)
Browse files Browse the repository at this point in the history
* Adds documentation about Signal Traps

* formatting

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
nunomaduro and taylorotwell authored Sep 13, 2022
1 parent 2e6ffef commit 5b0f8c3
Showing 1 changed file with 14 additions and 32 deletions.
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

0 comments on commit 5b0f8c3

Please sign in to comment.