I've got a php-script that i want to execute, only if an other instance of the script isn't already running. I've got this code:
$lockfile = __DIR__.'/lock.file';
if(file_exists($lockfile) == false)
{
echo 'no lockfile. Job will execute.';
$handle = fopen($lockfile, 'x') or die('Cannot open file: '.$lockfile);
$data = 'This is the lockfile';
fwrite($handle, $data);
fclose($lockfile);
createLinks();
unlink($lockfile);
}
else
{
echo 'Lockfile present, job will not execute. Please try again later';
}
But it doesn't correctly check if the file exists. If i call the script with my browser, the lock.file is correctly created (i can see it with ftp), and afterwards deleted. However, i still can run the script multiple times simultaneously. If i create a lock.file myself with ftp, it doesn't execute the script. I've been searching for hours now, what can it be? Maybe i'm stupid, but i think this should work, right?
Edit: Jep, flock did it. Thanks very much! Final code:
$lockfile = __DIR__.'/lock.file';
$handle = fopen($lockfile, "x");
if(flock($handle, LOCK_EX))
{
echo 'no lockfile. Job will execute.';
$data = 'This is the lockfile';
fwrite($handle, $data);
createLinks();
fclose($lockfile);
unlink($lockfile);
}
else
{
echo 'Lockfile present, job will not execute. Please try again later';
}