PHP Command Line - Avoid several Instances of your App.

Submitted by pure-php on Mon, 2005-03-21 23:39.

Since PHP 4, you can also write command line apps in php. If you have a critical app, and you want to avoid several, or mor than one instance of your app, to run, you can use the following class. It works only on unix and linux operating sytems.

Usage:

<?php
inlude
("ProcessHandler.class.php");
if(
ProcessHandler::isActive()){
   die(
"Already running!\n");
}else{
   
ProcessHandler::activate();
   
//run my app
}
?>

<?php
if (!defined('PID')) {
    
define("PID","/tmp/pid.php");
}
class 
ProcessHandler{
    function 
isActive(){
        
$pid ProcessHandler::getPID();
        if(
$pid == null){
            
$ret false;
        }else{
            
$ret posix_kill $pid);
        }
        if(
$ret == false){
            
ProcessHandler::activate();
        }
        return 
$ret;
    }
    function 
activate(){
        
$pidfile PID;
        
$pid ProcessHandler::getPID();
        if(
$pid != null && $pid == getmypid()){
            return 
"Already running!\n";
        }else{
            
$fp fopen($pidfile,"w+");
            if(
$fp){
                if(!
fwrite($fp,"<"."?php\n\$pid = ".getmypid().";\n?".">")){
                    die(
"Can not create pid file!\n");
                }
                
fclose($fp);
            }else{
                die(
"Can not create pid file!\n");
            }
        }
    }
    function 
getPID(){
        if(
file_exists(PID)){
            require(
PID);
            return 
$pid;
        }else{
            return 
null;
        }
    }
}
?>

add new comment
Submitted by Ryan Brooks (not verified) on Tue, 2005-03-22 17:51.

Why not just touch the file called the PID?

-Ryan

Submitted by pure-php on Tue, 2005-03-22 19:18.

Hi,
just touching the PID ist not alway enough. If another user kills the process, php is not able to touch the PID. The prcess is killed, you app is terminated, but the PID remaines untouched.

Submitted by Ryan Brooks (not verified) on Thu, 2005-03-24 01:41.

That's a veeery good point sir. Touche.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Datenschutz | Impressum