On my Linux server, I need to synchronize multiple scripts, written in BASH and PHP, so that only one of them is able to start a system-critical job, which is a series of BASH/PHP commands, that would mess things up if performed simultaneously by two or more scripts. From my experience with multithreading in C++, I’m familiar with the notion of mutex, but how do I implement a mutex for a bunch of scripts that run in separate processes and, of course, aren’t written in C++?
Well, the first solution that comes into mind would be making sure that each of the scripts initially creates a “lock flag” file to let other scripts know that the job is “locked” and then deletes the file after it’s done with the job. But, as I see it, the file writing and reading operations are required to be completely atomic to let this approach work out with a 100% probability, and the same requirement would apply to any other synchronization method. And I’m pretty sure that file writing/reading operations are not atomic, they are not atomic across all existing Linux/Unix systems at least.
So what is the most flexible and reliable way to synchronize concurrent BASH and PHP scripts?
I’m not a PHP programmer, but the documentation says it provides a portable version of
flockthat you can use. The first example snippet looks pretty close to what you want. Try this:Note that by default
flockwaits until it can acquire the lock. You can useLOCK_EX | LOCK_NBif you want it to exit immediately in the case where another copy of the program is already running.Using the name “/tmp/lock.txt” may be a security hole (I don’t want to think hard enough to decide whether it truly is) so you should probably choose a directory that can only be written to by your program.