Skip to content

Instantly share code, notes, and snippets.

@derflocki
Created July 31, 2014 07:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save derflocki/4299afe6cbcdf43d7e8f to your computer and use it in GitHub Desktop.
Save derflocki/4299afe6cbcdf43d7e8f to your computer and use it in GitHub Desktop.
<?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