Reputation: 2821
Ealier I used function in a seperate file that could be call by script for cron.
function processExists($file = false) {
$exists = false;
$file = $file ? $file : basename(__FILE__);
$command = "ps -ef | grep -v grep | grep $file";
exec($command, $pids);
if (count($pids) > 1) {
$exists = true;
}
return $exists;
}
It could be executed from any php script as:
if (processExists(basename(__FILE__))) {
echo 'Process in already running ';
exit(0);
}
For some reason it doesn't work in Debian6. Now I add in the beginning of every script:
$fh = fopen(__FILE__, 'r');
if (!flock($fh, LOCK_EX | LOCK_NB)) {
echo 'Script is already running!!!' . "\n";
exit(0);
}
It causes duplication of code in every script I tried to create function in a seperate file to call from any php script when neccessary, for example something like this:
function stopIfRunning($file)
{
$fh = fopen($file, 'r');
if(!flock($fh, LOCK_EX | LOCK_NB)) {
echo 'Script is already running!!!' . "\n";
exit(0);
}
}
And calling from php script:
stopIfRunning(__FILE__);
But it doesn't work in this case. Could you please explain why it doesn't work in this case?
Upvotes: 1
Views: 689
Reputation: 2821
It seems the problem is with $fh on stopIfRunning function. If the file with with functiona changed it with:
$fh = null;
function stopIfRunning($file)
{
global $fh;
echo $file, "\n";
$fh = fopen($file, 'r');
if (!$fh) {
echo 'Failed to open file', "\n";
}
if(!flock($fh, LOCK_EX | LOCK_NB)) {
echo 'Script is already running!!!' . "\n";
exit(0);
}
}
And call it in the file that should be launched using cron:
stopIfRunning(__FILE__);
Here global variable is used, which is not good. It would be great if somebody suggest a solution without global variable.
Upvotes: 0
Reputation: 1291
FILE it is name of running file.
stopIfRunning(__FILE__);
function stopIfRunning($file)
{
$fh = fopen($file, 'r');
....
}
Here you tried open this executed file for lock.
Upvotes: 0
Reputation: 11690
If you need to make sure the service is running, use Daemontools or Monit.
And personally, I would use plain Bash, not PHP, if custom implementation needed.
BTW, you can easily debug your ps
command in terminal.
Upvotes: 1