Created
July 31, 2014 07:50
-
-
Save derflocki/4299afe6cbcdf43d7e8f to your computer and use it in GitHub Desktop.
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 | |
/** | |
* php PID checker class for linux, using /proc/$PID/ for is-alive-check | |
* $pidchecker = new PIDChecker("/tmp/boku_accman_set_boku_mailbox.pid"); | |
* try { | |
* $pidchecker->check(); | |
* } catch(Exception $e) { | |
* print($e->getMessage())."\n"; | |
* die(); | |
* } | |
**/ | |
class PIDChecker { | |
protected $pidfile = null; | |
public function __construct($pidfile) { | |
$this->pidfile = (string)$pidfile; | |
} | |
protected function getOtherPid() { | |
return trim(file_get_contents($this->pidfile)); | |
} | |
protected function shouldStopExecution() { | |
$stop_execution = false; | |
if (file_exists($this->pidfile)) { | |
$pid = $this->getOtherPid(); | |
$stop_execution = file_exists('/proc/'.$pid); | |
} | |
return $stop_execution; | |
} | |
/** | |
* Check if another process is locking the PID file. If so throws an | |
* Exception. | |
* | |
* @throws Exception | |
*/ | |
public function check() { | |
if($this->shouldStopExecution()) { | |
throw new Exception(sprintf("PID file already exists and PID job is still running (PID: %d)", $this->getOtherPid())); | |
} else { | |
$success = @file_put_contents($this->pidfile, getmypid()."\n"); | |
if(($success === false) && (sfConfig::get('sf_environment') == "prod")) { | |
throw new Exception("Could not create pidfile. "); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment