Add daemon for process locking

This commit is contained in:
2011-12-31 02:09:26 +00:00
parent 3486deefd1
commit cef9d803cb
2 changed files with 54 additions and 0 deletions

View File

@@ -0,0 +1,50 @@
<?php
class SihnonFramework_Daemon {
protected $config;
protected $lock_file;
protected $lock;
protected $locked;
public function __construct(SihnonFramework_Config $config) {
$this->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);
}
}
?>

View File

@@ -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 {};
?>