Last active
January 26, 2024 15:07
-
-
Save sokil/d9bee00ac2b6d76dbf5457eb820b200a to your computer and use it in GitHub Desktop.
Handle signals by dispatcher or ticks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* START: Handle by ticks */ | |
declare(ticks=1); | |
function tick_handler() { echo "T"; } | |
register_tick_function('tick_handler'); | |
/* END: Handle by ticks */ | |
// register handler for all signals | |
for ($sig = 0; $sig <=32; $sig++) { | |
pcntl_signal($sig, function($sig) { | |
echo "Signal" . $sig; | |
}); | |
} | |
// start main loop | |
while(true) { | |
/* START: Handle by signal dispatch */ | |
pcntl_signal_dispatch(); | |
/* END: Handle by signal dispatch */ | |
echo '.'; | |
sleep(1); | |
echo '-'; | |
sleep(1); | |
echo '-'; | |
sleep(1); | |
echo '-'; | |
sleep(1); | |
echo '-'; | |
sleep(1); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class SignalHandler | |
{ | |
/** | |
* @var bool | |
*/ | |
private $isRunning; | |
/** | |
* @param \Closure|null $callback | |
*/ | |
public function __construct(\Closure $callback = null) | |
{ | |
if (php_sapi_name() === 'cli') { | |
$handle = function ($signal) use ($callback) { | |
$this->isRunning = false; | |
if ($callback) { | |
call_user_func_array($callback, [$signal]); | |
} | |
}; | |
pcntl_signal(SIGINT, $handle); | |
pcntl_signal(SIGTERM, $handle); | |
pcntl_signal(SIGHUP, $handle); | |
pcntl_signal(SIGUSR1, $handle); | |
} | |
$this->isRunning = true; | |
} | |
/** | |
* @return bool | |
*/ | |
public function isRunning(): bool | |
{ | |
if (php_sapi_name() === 'cli') { | |
pcntl_signal_dispatch(); | |
} | |
return $this->isRunning; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment