Skip to content

Commit

Permalink
Register shutdown function to kill process in the event of an early e…
Browse files Browse the repository at this point in the history
…xit (#76)

* register shutdown function to kill process in the case of an early exit

* Restore cursor on exit

* Simplify killing of child process

---------

Co-authored-by: Jess Archer <jess@jessarcher.com>
  • Loading branch information
joetannenbaum and jessarcher authored Sep 20, 2023
1 parent a1f16f1 commit a9a7bb7
Showing 1 changed file with 10 additions and 11 deletions.
21 changes: 10 additions & 11 deletions src/Spinner.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,16 +42,15 @@ public function spin(Closure $callback): mixed
{
$this->capturePreviousNewLines();

register_shutdown_function(fn () => $this->restoreCursor());

if (! function_exists('pcntl_fork')) {
return $this->renderStatically($callback);
}

$originalAsync = pcntl_async_signals(true);

pcntl_signal(SIGINT, function () {
$this->showCursor();
exit();
});
pcntl_signal(SIGINT, fn () => exit());

try {
$this->hideCursor();
Expand All @@ -68,14 +67,18 @@ public function spin(Closure $callback): mixed
usleep($this->interval * 1000);
}
} else {
register_shutdown_function(fn () => posix_kill($pid, SIGHUP));

$result = $callback();

$this->resetTerminal($originalAsync, $pid);
posix_kill($pid, SIGHUP);

$this->resetTerminal($originalAsync);

return $result;
}
} catch (\Throwable $e) {
$this->resetTerminal($originalAsync, $pid ?? null);
$this->resetTerminal($originalAsync);

throw $e;
}
Expand All @@ -84,12 +87,8 @@ public function spin(Closure $callback): mixed
/**
* Reset the terminal.
*/
protected function resetTerminal(bool $originalAsync, ?int $pid): void
protected function resetTerminal(bool $originalAsync): void
{
if ($pid) {
posix_kill($pid, SIGHUP);
}

pcntl_async_signals($originalAsync);
pcntl_signal(SIGINT, SIG_DFL);

Expand Down

0 comments on commit a9a7bb7

Please sign in to comment.