PHP Command Line - Avoid several Instances of your App.

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;
        }
    }
}
?>

3 comments | read more

Reply

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.

Datenschutz | Impressum