2

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.

4
  • You are not allowed to write to /tmp? Seriously? What does sys_get_temp_dir() give you, and can you write there? Commented Mar 6, 2013 at 13:40
  • Memcache, Redis, hell - even MySQL if you have to. You don't have access to ANY data storage engine? Commented Mar 6, 2013 at 13:43
  • Is posix_mkfifo an option? Its advantage over memcached, APC and co. is that it's enabled by default. Commented Mar 6, 2013 at 13:45
  • You know, I haven't even thought about using the database for a locking mechanism... Commented Mar 6, 2013 at 13:49

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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)
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?
@Bogdan Yeah, anything between LOCK_EX and LOCK_UN can be seen as the critical section.
@Bogdan If you want the script to quit whenever there's a lock you can use LOCK_EX | LOCK_NB instead.
0

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

do you have mysql access? store the block as a row in a table instead. you could also use APC, or memcached.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.