Skip to content

Commit 5b0f8c3

Browse files
[9.x] Adds documentation about Signal Traps 🚦 (#8178)
* Adds documentation about Signal Traps * formatting Co-authored-by: Taylor Otwell <[email protected]>
1 parent 2e6ffef commit 5b0f8c3

File tree

1 file changed

+14
-32
lines changed

1 file changed

+14
-32
lines changed

Diff for: ‎artisan.md

+14-32
Original file line numberDiff line numberDiff line change
@@ -615,47 +615,29 @@ If you would like to call another console command and suppress all of its output
615615
<a name="signal-handling"></a>
616616
## Signal Handling
617617

618-
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.
619-
620-
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`:
621-
622-
```php
623-
<?php
624-
625-
use Symfony\Component\Console\Command\SignalableCommandInterface;
626-
627-
class StartServer extends Command implements SignalableCommandInterface
628-
{
629-
// ...
630-
631-
/**
632-
* Get the list of signals handled by the command.
633-
*
634-
* @return array
635-
*/
636-
public function getSubscribedSignals(): array
637-
{
638-
return [SIGINT, SIGTERM];
639-
}
618+
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:
640619

641620
/**
642-
* Handle an incoming signal.
621+
* Execute the console command.
643622
*
644-
* @param int $signal
645-
* @return void
623+
* @return mixed
646624
*/
647-
public function handleSignal(int $signal): void
625+
public function handle()
648626
{
649-
if ($signal === SIGINT) {
650-
$this->stopServer();
627+
$this->trap(SIGTERM, fn () => $this->shouldKeepRunning = false);
651628

652-
return;
629+
while ($this->shouldKeepRunning) {
630+
// ...
653631
}
654632
}
655-
}
656-
```
657633

658-
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.
634+
To listen for multiple signals at once, you may provide an array of signals to the `trap` method:
635+
636+
$this->trap([SIGTERM, SIGQUIT], function ($signal) {
637+
$this->shouldKeepRunning = false;
638+
639+
dump($signal); // SIGTERM / SIGQUIT
640+
});
659641

660642
<a name="stub-customization"></a>
661643
## Stub Customization

0 commit comments

Comments
 (0)