Let's get right down to business by unveiling a sample code that you can adapt to your needs.
class SingleInstanceProcess
{
private $pid_file;
public $is_ok;
function __construct()
{
global $argv;
$this->is_ok = 0;
$my_name = basename($argv[0]);
$this->pid_file = "/tmp/$my_name.pid";
$pid = getmypid(); if (!$pid) exit(1);
$this->is_ok = 1;
if (file_exists($this->pid_file))
{
$old_pid = file_get_contents($this->pid_file);
$cmd = "ps -Cp $old_pid | grep $my_name";
$result = trim(`$cmd`);
$t_result = explode(" ",$result);
$result = $t_result[0];
if ($old_pid==$result) // Old process is running or accepable issue:
{ // If the old process was killed ( e.g. kill -9 or power failure and /tmp not cleaned)
$this->is_ok = 0; // and another program with excactly the same name is running
return; // with exactly the same pid as the previous killed process...
// (practicaly, the probability that this happens is negligible.)
} // we may wrongly suppose that an instance is running ...
}
file_put_contents($this->pid_file, $pid);
chmod($this->pid_file,0777);
}
public function __destruct()
{
if($this->is_ok && file_exists($this->pid_file)) unlink($this->pid_file);
}
}
$single_instance_process = new SingleInstanceProcess;
if (!$single_instance_process->is_ok) exit(0);
By naming this script single_instance.php
You just have to do an include in your script, and it will only run if there is no another instance of that script already running!
#!/usr/bin/php
< ?php
// here my script whatever.php
include "/path/single_instance.php";
// my code here
? >
|