1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 90: 91: 92: 93: 94: 95: 96: 97: 98: 99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131:
<?php
namespace SAREhub\Commons\Process;
class PcntlSignals
{
const SIGHUP = 1;
const SIGINT = 2;
const SIGTERM = 15;
const SIGPIPE = 13;
const SIGUSR1 = 10;
const DEFAULT_NAMESPACE = 'default';
private $handlers = [];
public static function create($install = true)
{
$instance = new PcntlSignals();
if ($install) {
$instance->install(self::getDefaultInstalledSignals());
}
return $instance;
}
public static function getDefaultInstalledSignals()
{
return [self::SIGHUP, self::SIGINT, self::SIGTERM, self::SIGPIPE, self::SIGUSR1];
}
public function install(array $signals)
{
if (self::isSupported()) {
$callback = [$this, 'dispatchSignal'];
foreach ($signals as $signal) {
\pcntl_signal($signal, $callback);
}
};
}
public function handle($signal, $handler, $namespace = self::DEFAULT_NAMESPACE)
{
if (empty($this->handlers[$signal])) {
$this->handlers[$signal] = [];
}
if (empty($this->handlers[$signal][$namespace])) {
$this->handlers[$signal][$namespace] = [];
}
$this->handlers[$signal][$namespace][] = $handler;
return $this;
}
public function dispatchSignal($signal)
{
if (isset($this->handlers[$signal])) {
foreach ($this->handlers[$signal] as $namespaceHandlers) {
foreach ($namespaceHandlers as $handler) {
$handler();
}
}
}
return $this;
}
public function getHandlers()
{
return $this->handlers;
}
public function getHandlersForSignal($signal, $namespace = null)
{
return isset($this->handlers[$signal]) ? $this->handlers[$signal] : [];
}
public function checkPendingSignals()
{
if (self::isSupported()) {
\pcntl_signal_dispatch();
}
}
public static function isSupported()
{
return !defined('PHP_WINDOWS_VERSION_MAJOR');
}
}