I am working with the following code on a PHP script:
try{
if(file_exists($dir."pid.txt"))throw new Exception("Process is already running");
}
catch(Exception $e){
die("Warning: ".$e->getMessage()." in ".$e->getFile()." on line ".$e->getLine());
}
touch($dir."pid.txt");
sleep(20); // Just for a proof of concept
Basically what the script does is:
If the file $dir."pid.txt"
- where $dir
contains a directory with the right permissions - already exists, kill the script. If not, create the pid.txt
file and sleep during 20 seconds.
The intended effect is to prevent this script from being accessed twice.
If I open the script in one tab and try again in another tab within that 20 seconds period, the script on the second tab won't die. However, different tabs in different browsers do work. I have been trying with Chrome, Firefox, and IE, latest stable release versions.
I am 100% sure that the file "pid.txt" has been created correctly by the first script.
I suspect it has something to do with the try/catch statement because if I do
if(file_exists($dir."pid.txt"))die("The process is already running");
it does work. However, this is one of many possible errors and I would like to group them in a try/catch statement. That's why I don't want to proceed with this last approach.
Ideas?