Skip to content

Commit

Permalink
Merge pull request #16 from joelvh/patch-1
Browse files Browse the repository at this point in the history
Trap signals rather than killing processes
  • Loading branch information
freekmurze committed Jun 15, 2023
2 parents 90bad10 + f83c0b8 commit 9ae568e
Showing 1 changed file with 12 additions and 24 deletions.
36 changes: 12 additions & 24 deletions src/Commands/WatchHorizonCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,20 @@ class WatchHorizonCommand extends Command
{
protected Process $horizonProcess;

protected $signature = 'horizon:watch {--without-tty : Disable output to TTY}}';
protected $signature = 'horizon:watch {--without-tty : Disable output to TTY}';

protected $description = 'Run Horizon and restart it when PHP files are changed';

protected $trappedSignal = null;

public function handle()
{
$this->components->info('Starting Horizon and will restart it when any files change...');

$this->trap([SIGINT, SIGTERM], function ($signal): void {
$this->trappedSignal = $signal;
});

$horizonStarted = $this->startHorizon();

if (! $horizonStarted) {
Expand Down Expand Up @@ -48,6 +54,9 @@ protected function listenForChanges(): self
$this->restartHorizon();
}
})
->shouldContinue(function () {
return $this->trappedSignal === null;
})
->start();

return $this;
Expand All @@ -72,7 +81,8 @@ protected function restartHorizon(): self
{
$this->components->info('Change detected! Restarting horizon...');

$this->stopHorizon();
$this->horizonProcess->stop();

$this->startHorizon();

return $this;
Expand All @@ -82,26 +92,4 @@ protected function isPhpFile(string $path): bool
{
return str_ends_with(strtolower($path), '.php');
}

protected function stopHorizon(): void
{
$this->killStrayHorizonProcesses();

$this->horizonProcess->stop();
}

protected function killStrayHorizonProcesses(): void
{
(Process::fromShellCommandline('pgrep -P '.$this->horizonProcess->getPid()))
->run(function ($type, $output) {
$childPids = explode("\n", $output);
foreach ($childPids as $childPid) {
if (! $childPid) {
continue;
}

(Process::fromShellCommandline('kill '.$childPid))->run();
}
});
}
}

0 comments on commit 9ae568e

Please sign in to comment.