1

I have a PHP page that should be accessible only by one user at a time. It's a kind of "poor man's cron": A "Javascript" file, that is requested in the background. At the moment I'm thinking of creating a lock file like this:

if(file_exists($lockfile) && filemtime($lockfile) + EXPIRES_AFTER > time() ) {
    die("// Page is locked.");
}

touch($lockfile);
// do stuff
unlink($lockfile);
echo "// Cron stuff was run";

But I'm not sure if there could be a very short window of opportunity between the file_exists and the touch call where another page request could check for the file existence and see that it isn't there. We're probably talking microseconds here so I would like top know at which amount of requests I really need to start worrying.

4

3 に答える 3

3

There is no atomicity in the code you wrote, so yes, there is a race condition.

于 2012-08-05T10:13:28.897 に答える
3

If you want to do this really precisely, then use a different approach, because there IS some time between the check and the lock.

Two possible implementations:

  1. Use flock: https://secure.php.net/manual/en/function.flock.php

  2. Use something like STM: E.g. open the lockfile for append, write something into it, close the handle. Then read the file back, and if it only has what you wrote into it then you have acquired the lock.

Other than that, your original code would probably not cause any problems.

于 2012-08-05T10:19:21.420 に答える
1

Your code has a race condition. Instead, dio_open the file with O_EXCL. This will fail if the file already exists. Unlink it when you're done.

The only thing to watch out for is if the system or the script crashes while the file exists, the script will never run again. If you are worried about this, check the age of the file (if you fail to create it) and if it's older than the longest the script could ever take, unlink it.

Using flock is another option.

于 2012-08-05T10:33:44.657 に答える