Skip to content
Merged
Show file tree
Hide file tree
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: 46 additions & 0 deletions src/CLI.php
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,52 @@ public static function spinner(int $frame = 0, bool $finalize = false) : void
static::liveLine($frames[$frame % \count($frames)]);
}

/**
* Register a handler for the given POSIX signal when pcntl is available.
*
* @param int $signal The signal number
* @param callable $handler The signal handler
*
* @return bool True if the handler was registered, false if pcntl is unavailable
*/
public static function onSignal(int $signal, callable $handler) : bool
{
if (!\function_exists('pcntl_signal')) {
return false;
}
return \pcntl_signal($signal, $handler, true);
}

/**
* Register a cleanup handler for the interrupt signal (Ctrl+C) when available.
*
* @param callable $handler The signal handler
*
* @return bool True if the handler was registered
*/
public static function onSigint(callable $handler) : bool
{
if (!\defined('SIGINT')) {
return false;
}
return static::onSignal(\SIGINT, $handler);
}

/**
* Restore the default handler for a POSIX signal when pcntl is available.
*
* @param int $signal The signal number
*
* @return bool True if the handler was restored
*/
public static function restoreSignal(int $signal) : bool
{
if (!\function_exists('pcntl_signal')) {
return false;
}
return \pcntl_signal($signal, \SIG_DFL);
}

/**
* Performs audible beep alarms.
*
Expand Down
10 changes: 10 additions & 0 deletions tests/CLITest.php
Original file line number Diff line number Diff line change
Expand Up @@ -266,4 +266,14 @@ public function testSpinner() : void
self::assertStringContainsString('|', Stdout::getContents());
CLI::setAnsi(true);
}

public function testSignals() : void
{
$term = \defined('SIGTERM') ? \SIGTERM : 15;
self::assertIsBool(CLI::onSignal($term, static function () : void {
}));
self::assertIsBool(CLI::onSigint(static function () : void {
}));
self::assertIsBool(CLI::restoreSignal($term));
}
}
Loading