3

After much digging around I haven't been able to identify the issue behind a race condition I'm finding on a little PHP pseudo-cron.

The code looks like this:

fh = fopen(ROOT . '.cron.lock', 'w+');
if (flock($fh, LOCK_EX|LOCK_NB)) {
    //Cron logic goes here
    flock($fh, LOCK_UN);
}

It should be pretty straightforward, and usually does work. The point is that every so often, this little cron executes twice (sending a duplicate email to a user), which is rather annoying.

Initially I thought I'd have to use the third $ewouldblock parameter. But this has turned out not to work, just causing the cron to execute always without regard for any other process.

Whenever I test this code in a CLI environment, it works perfectly fine. But it won't as soon as I move over to using the script inside a HTTPD (Apache) request.

http://php.net/manual/en/function.flock.php

If anyone can help, or maybe give me a pointer what the whole $ewouldblock parameter is about (since the documentation is not very straightforward about it) I would appreciate a lot.

César
  • 370
  • 1
  • 9
  • 1
    Good description of $eawouldblock could be found in [that](http://stackoverflow.com/questions/24425247/difference-between-return-value-of-non-blocking-flock-function-and-the-wouldblo?answertab=votes#tab-top) topic. Which OS, apache mpm are you using? PHP doc states that "When using a multithreaded server API like ISAPI you may not be able to rely on flock() to protect files against other PHP scripts running in parallel threads of the same server instance!". So, if you're using multithreaded apache mpm, that could be your case. – Evgeny Soynov Mar 01 '16 at 14:47
  • It's the HTTPD that comes preloaded with CentOS. It seems that flock without LOCK_NB works fine for me, but it obviously will keep several processes running while the cron is executing in one of them. I originally intended to "skip" the cron if it's already executing, letting the other processes finish while the cron was executed on one of them. – César Mar 02 '16 at 10:13
  • Also, read through the post you linked. That confirms that my issue is not related to the ewouldblock variable and the code should be working properly. – César Mar 02 '16 at 10:15
  • @César did you end up resolving the race condition? – Jethro Cao Dec 06 '20 at 03:54

0 Answers0