From cef9d803cb2cef11d69d6b77fb1ba5c600ec50cc Mon Sep 17 00:00:00 2001 From: Ben Roberts Date: Sat, 31 Dec 2011 02:09:26 +0000 Subject: [PATCH] Add daemon for process locking --- source/lib/SihnonFramework/Daemon.class.php | 50 +++++++++++++++++++ .../lib/SihnonFramework/Exceptions.class.php | 4 ++ 2 files changed, 54 insertions(+) create mode 100644 source/lib/SihnonFramework/Daemon.class.php diff --git a/source/lib/SihnonFramework/Daemon.class.php b/source/lib/SihnonFramework/Daemon.class.php new file mode 100644 index 0000000..0fc3d5b --- /dev/null +++ b/source/lib/SihnonFramework/Daemon.class.php @@ -0,0 +1,50 @@ +config = $config; + $this->lock_file = $config->get('daemon.lock-file'); + $this->lock = null; + $this->locked = false; + + $this->init(); + } + + public function __destruct() { + $this->teardown(); + } + + protected function init() { + $this->lock = fopen($this->lock_file, 'w'); + $wouldBlock = false; + + $result = flock($this->lock, LOCK_EX|LOCK_NB, $wouldBlock); + if ($wouldBlock) { + // Another instance is already running + throw new SihnonFramework_Exception_AlreadyRunning(); + } else if ( ! $result) { + throw new SihnonFramework_Exception_LockingFailed(); + } + + + } + + protected function teardown() { + if ( ! $this->locked) { + return; + } + + flock($this->lock, LOCK_UN); + fclose($this->lock); + unlink($this->lock_file); + } +} + +?> \ No newline at end of file diff --git a/source/lib/SihnonFramework/Exceptions.class.php b/source/lib/SihnonFramework/Exceptions.class.php index bf0b0a0..c67f4d3 100644 --- a/source/lib/SihnonFramework/Exceptions.class.php +++ b/source/lib/SihnonFramework/Exceptions.class.php @@ -48,4 +48,8 @@ class SihnonFramework_Exception_ValidationException extends SihnonFramework_E class SihnonFramework_Exception_InvalidContent extends SihnonFramework_Exception_ValidationException {}; class SihnonFramework_Exception_InvalidLength extends SihnonFramework_Exception_ValidationException {}; +class SihnonFramework_Exception_DaemonException extends SihnonFramework_Exception {}; +class SihnonFramework_Exception_AlreadyRunning extends SihnonFramework_Exception_DaemonException {}; +class SihnonFramework_Exception_LockingFailed extends SihnonFramework_Exception_DaemonException {}; + ?>