Linux concurrency scripting with mutexes Linux concurrency scripting with mutexes linux linux

Linux concurrency scripting with mutexes


I'm not a PHP programmer, but the documentation says it provides a portable version of flock that you can use. The first example snippet looks pretty close to what you want. Try this:

<?php$fp = fopen("/tmp/lock.txt", "r+");if (flock($fp, LOCK_EX)) {  // acquire an exclusive lock    // Do your critical section here, while you hold the lock    flock($fp, LOCK_UN);    // release the lock} else {    echo "Couldn't get the lock!";}fclose($fp);?>

Note that by default flock waits until it can acquire the lock. You can use LOCK_EX | LOCK_NB if 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.


You can use flock to atomically lock your flag file. The -e option is to acquire an exclusive lock.

From the man page:

By default, if the lock cannot be immediately acquired, flock waits until the lock is available.

So if all your bash/php scripts try to lock the file exclusively, only one can successfully acquire it and rest of them would wait for the lock.

If you don't want to wait thenuse -w to timeout.


fuser-based lock in Bash (it guarantees that no two processes access the protected resource at the same time but may result in negative locking attempt even if no processes access the resource, almost improbable though):

#!/bin/bashset -eufunction mutex { local file=$1 pid pids exec 8>>"$file" { pids=$(/sbin/fuser -f "$file"); } 2>&- 9>&- for pid in $pids; do   [[ $pid = $$ ]] && continue   exec 8>&-   return 1 # locked by other pid done}