Advertisement
iarmin

PHP single instance

Aug 11th, 2012
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.75 KB | None | 0 0
  1. # PHP Process class for single instance scripts
  2. # source: http://blog.crazytje.be/single-instance-php-script/
  3.  
  4. # process class
  5.  
  6. class Process {
  7.     private $strPIDFile;
  8.  
  9.     function __construct($pProcessIdFile) {
  10.         $this->strPIDFile = $pProcessIdFile;
  11.         if(file_exists($this->strPIDFile)) {
  12.             if(!is_writable($this->strPIDFile)) {
  13.                 throw new Exception('File Not Writable', 101);
  14.             }
  15.  
  16.             $pid = trim(file_get_contents($this->strPIDFile));
  17.             if(posix_kill($pid, 0)) {
  18.                 if($this->is_alive($pid)) {
  19.                     //process is alive
  20.                     throw new Exception('Process Already Running', 100);
  21.                 } else {
  22.                     //cleanup
  23.                     unlink($this->strPIDFile);
  24.                 }
  25.             }
  26.         } else {
  27.             if(!is_writable(dirname($this->strPIDFile))) {
  28.                 throw new Exception('Directory Is Not Writeable', 102);
  29.             }
  30.         }
  31.  
  32.         $id = getmypid();
  33.         file_put_contents($this->strPIDFile, $id);
  34.  
  35.     }
  36.  
  37.     public function __destruct() {
  38.         if(file_exists($this->strPIDFile)) {
  39.             unlink($this->strPIDFile);
  40.         }
  41.     }
  42.  
  43.     private function is_alive($pId){
  44.         exec('ps '.$pId, $ProcessState);
  45.         return(count($ProcessState) >= 2);
  46.     }
  47. }
  48.  
  49.  
  50. # example
  51. try {
  52.     $Process = new Process('/tmp/myphpscript.pid');
  53. } catch(Exception $ex) {
  54.     switch($ex->getCode()) {
  55.         case 100:
  56.             echo 'Script already running...';
  57.             return;
  58.         case 101:
  59.             echo 'File Not Writable';
  60.             return;
  61.         case 102:
  62.             echo 'Folder Not Writable';
  63.             return;
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement