My use for flock is because we have N simultaneous processes starting that all need read access to a file. If the file doesn't exist, we need to create it, but only one process can do that, or else they would be writing all over each other.
The normal example of how to do that using Linux's flock
is like this:
(
flock -n 9 || exit 1
if [ ! -f file.txt ]; then
echo 'Simulate the file creation' > file.txt
fi
) 9>/var/lock/mylockfile
However, this is very confusing to read, especially if you're not familiar with subshells and file descriptors. I'm wondering if it's possible to manually lock and unlock the file:
flock --exclusive file.txt
if [ ! -f file.txt ]; then
echo 'Simulate the file creation' > file.txt
fi
flock --unlock file.txt
If not, is there some similar way to use flock
, that's as readable as possible, avoiding subshells, exec
, etc?