Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace PidControl;
- class PidControl {
- protected $maxRunSec;
- protected $pidFile;
- function __construct($maxRunSec, $pidFile = false) {
- $this->setMaxRunSec($maxRunSec);
- if($pidFile === false) {
- $this->setPidFile(__FILE__ . '.pid');
- } else {
- $this->setPidFile($pidFile);
- }
- }
- /*
- * Use symlinking/atomic operations to prevent rare race conditions
- */
- public function writePid() {
- if(is_dir(dirname($this->getPidFile())) && is_writable(dirname($this->getPidFile()))) {
- return file_put_contents($this->getPidFile(), time() . ';' . getmypid());
- } else {
- throw new \Exception('PID File Not Writable: ' . $this->getPidFile());
- }
- }
- public function cleanupPid() {
- unlink($this->getPidFile());
- }
- public function start() {
- if(!is_file($this->getPidFile())) {
- $this->writePid();
- return true;
- } else {
- $pidData = file_get_contents($this->getPidFile());
- $pidPieces = explode(';', $pidData);
- if(!empty($pidData) && count($pidPieces) === 2) {
- list($time, $existingPid) = $pidPieces;
- if(is_dir("/proc/" . $existingPid)) {
- throw new \Exception("PID File and /proc both say process id $existingPid is still running. "
- . "PID file indicates it has been running since " . date('r', $time));
- } else {
- if(($time + $this->getMaxRunSec()) < time()) {
- $this->writePid();
- trigger_error("PID file exists but seems to be stale, bravely proceeding and updating PID "
- . "file.", E_USER_WARNING);
- return true;
- } else {
- throw new \Exception("PID file exists, the PID no longer exists but I have not exceeded my "
- . "timeout of " . $this->getMaxRunSec() . " seconds.");
- }
- }
- } else {
- throw new \Exception("PID file exists but isn't the proper format, I don't know what to do!");
- }
- }
- return false;
- }
- public function end() {
- $this->cleanupPid();
- }
- public function setMaxRunSec($secs) {
- $this->maxRunSec = $secs;
- }
- public function getMaxRunSec() {
- return $this->maxRunSec;
- }
- public function setPidFile($file) {
- $this->pidFile = $file;
- }
- public function getPidFile() {
- return $this->pidFile;
- }
- }
- // EXAMPLE USAGE:
- $pidControl = new PidControl(3600);
- try {
- $pidControl->start();
- } catch(Exception $e) {
- }
- // CODE CODE
- $pidControl->end();
Advertisement
Add Comment
Please, Sign In to add comment