imprint
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, 0 );
}
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;
}
}
}
?>
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.
Why not just touch the file called the PID?
-Ryan