I'm using a php script to read emails recieved by my application's bounce address and do stuff with them. The script is scheduled to run with cron jobs but I have no control over it and I don't have permission to write files on the server (so that pretty much eliminates the file locking mechanism). Is there another way to ensure I have only one instance of the script running at any given time? The server is running linux.
2 Answers
I suppose you could try this:
// we use ourselves as the lock file
if (false === ($f = fopen(__FILE__, 'r'))) {
die("Could not open lock file");
}
if (false === flock($f, LOCK_EX)) {
die("Could not obtain lock");
}
// do your stuff
flock($f, LOCK_UN);
fclose($f);
You don't need write access to work with advisory locks; this is of course assuming that flock() is enabled in your configuration.
4 Comments
Bogdan
I tried this, can run 2 or more instances just fine (using sleep because the script is pretty fast when there's little traffic). flock seems to work fine. Also it seems like they wait for eachother since the second instance only sleeps after the first one is done sleeping (might have something to do with usleep tho, I rarely use it)
Bogdan
more info for above comment: it seems like the wait happens at the flock($f, LOCK_EX) line, so instead of entirely blocking the 2nd instance it just delays it?
Ja͢ck
@Bogdan Yeah, anything between LOCK_EX and LOCK_UN can be seen as the critical section.
Ja͢ck
@Bogdan If you want the script to quit whenever there's a lock you can use
LOCK_EX | LOCK_NB instead.its a little bit dirty but
if(file_exists("block.bin")) {
//already running
}
file_put_contents("block.bin", 1);
//do stuff
unlink("block.bin");
1 Comment
bizzehdee
do you have mysql access? store the block as a row in a table instead. you could also use APC, or memcached.
/tmp? Seriously? What doessys_get_temp_dir()give you, and can you write there?posix_mkfifoan option? Its advantage over memcached, APC and co. is that it's enabled by default.