I have been working on a shell script that manages lxc-containers, and came across a use case last where it is possible for two yum processes to interfere with each other. To ensure that only one yum process is run at a single point in time, I implemented file based locks using flock(1). Flock makes this super easy, since it has a “-x” option to create an exclusive lock (this is the default), and a “-n” option which causes flock to exit with a return code of 1 if it can’t obtain the lock. This allow code similar to the following to be used to protect sensitive areas:
(
flock -n -x 200
if [ $? != "0" ]; then
echo "ERROR: Unable to acquire the yum lock. Is another yum running?"
exit 1
fi
# Do yum stuff here
) 200>${TMP_DIR}/yum.lck
In my case this tiny bit of code ensures that only one yum process is able to run, which helps keep my package database in a sane state.