Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # PHP Process class for single instance scripts
- # source: http://blog.crazytje.be/single-instance-php-script/
- # process class
- class Process {
- private $strPIDFile;
- function __construct($pProcessIdFile) {
- $this->strPIDFile = $pProcessIdFile;
- if(file_exists($this->strPIDFile)) {
- if(!is_writable($this->strPIDFile)) {
- throw new Exception('File Not Writable', 101);
- }
- $pid = trim(file_get_contents($this->strPIDFile));
- if(posix_kill($pid, 0)) {
- if($this->is_alive($pid)) {
- //process is alive
- throw new Exception('Process Already Running', 100);
- } else {
- //cleanup
- unlink($this->strPIDFile);
- }
- }
- } else {
- if(!is_writable(dirname($this->strPIDFile))) {
- throw new Exception('Directory Is Not Writeable', 102);
- }
- }
- $id = getmypid();
- file_put_contents($this->strPIDFile, $id);
- }
- public function __destruct() {
- if(file_exists($this->strPIDFile)) {
- unlink($this->strPIDFile);
- }
- }
- private function is_alive($pId){
- exec('ps '.$pId, $ProcessState);
- return(count($ProcessState) >= 2);
- }
- }
- # example
- try {
- $Process = new Process('/tmp/myphpscript.pid');
- } catch(Exception $ex) {
- switch($ex->getCode()) {
- case 100:
- echo 'Script already running...';
- return;
- case 101:
- echo 'File Not Writable';
- return;
- case 102:
- echo 'Folder Not Writable';
- return;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement