From 62c3503abba03a6f34c5d95776e636ed76f632a7 Mon Sep 17 00:00:00 2001 From: Daniel Lowrey Date: Tue, 22 Apr 2014 20:45:20 -0400 Subject: [PATCH] Add libevent onSignal handler --- lib/LibeventReactor.php | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/lib/LibeventReactor.php b/lib/LibeventReactor.php index c802921..17329ed 100755 --- a/lib/LibeventReactor.php +++ b/lib/LibeventReactor.php @@ -16,6 +16,7 @@ class LibeventReactor implements Reactor { private static $TYPE_STREAM = 0; private static $TYPE_ONCE = 1; private static $TYPE_REPEATING = 2; + private static $TYPE_SIGNAL = 3; public function __construct() { $this->lastWatcherId = PHP_INT_MAX * -1; @@ -204,6 +205,40 @@ class LibeventReactor implements Reactor { }; } + public function onSignal($signal, callable $callback) { + $watcherId = ++$this->lastWatcherId; + $eventResource = event_new(); + $watcher = new LibeventWatcher; + $watcher->id = $watcherId; + $watcher->type = self::$TYPE_SIGNAL; + $watcher->eventResource = $eventResource; + $watcher->callback = $callback; + + $watcher->wrapper = $this->wrapSignalCallback($watcher); + + $this->watchers[$watcherId] = $watcher; + + event_set($eventResource, $signal, EV_SIGNAL | EV_PERSIST, $watcher->wrapper); + event_base_set($eventResource, $this->base); + event_add($eventResource); + + return $watcherId; + } + + private function wrapSignalCallback(LibeventWatcher $watcher) { + $callback = $watcher->callback; + $watcherId = $watcher->id; + + return function() use ($callback, $watcherId) { + try { + $callback($watcherId, $this); + } catch (\Exception $e) { + $this->stopException = $e; + $this->stop(); + } + }; + } + public function cancel($watcherId) { if (!isset($this->watchers[$watcherId])) { return;