tags:

views:

141

answers:

1

I can't seem to figure this one out.

I have a validator-type script that validates certain files on my server (checks if exists, its contents, etc). I want it to run continuously with only one instance of it, not more. The current solution I have doesn't seem to work, I'm guessing due to timeouts (possibly other reasons too). For each file that I validate, I set the php timeout to 60 seconds. I have this at the top of the script:

    $trigger_file2 = 'path/to/a/randomfile';

    if (file_exists($trigger_file2)){
        //another script is working, exit
                exit;
    }

    // create file inside app
    $handle = fopen($trigger_file2, 'w');
    fwrite($handle, '0');
    fclose($handle);

At the end of the script, I just use an unlink() on the trigger file. Due to possible timeouts, and possibly other reasons, the trigger file isn't always getting deleted and is causing problems. I also tried adding code that checks the time the trigger file was modified, and if older than 10 minutes, is deleted, but this is really inefficient, as the problem occurs often.

Any ideas on how to get around this? I thought of doing something with PIDs of running scripts, but I'm using CakePHP for the script, so every process looks like it's using index.php (I think).

Any other ideas on how to do this? Help would be immensely appreciated.

+1  A: 

I suggest you make the lock not the file itself, but an actual file lock.

$fp = fopen($trigger_file2, "r+");

if (!flock($fp, LOCK_EX | LOCK_NB)) {
    die("another script running");
}

LOCK_NB isn't respected on Windows, but you don't seem to be using it.

Artefacto
Thanks for the help!Just to make sure, is the code you posted above enough for the entire script? It's possible to create a lock on a file that doesn't even exist? I'm just not 100% on how to use this. I read the manual on flock, but a simple explanation would be great!Thanks a lot.
@user371699 Just prepend your script with that. As I put it, `fopen` fails if the file doesn't exist, both you can open it in write mode to force its creation.
Artefacto