Skip to content

Using Linux command lockfile in bash scripts

I needed to create a script that runs a regression test. I intended to schedule this with a cron job. However, I found that sometimes, my cron jobs would collide with each other.

So, I looked to Linux’ lockfile command to create a file lock as a semaphore.

Here’s the incantation:

[cc_bash]

# if we’re already running, exit
if ! lockfile -r 0 regression.lock; then
echo “regression.sh already running in area $1”
exit 1
fi
./tools/regression.py
rm -f regression.lock

[/cc_bash]
In this case, lockfile is set with a retry count of 0 -r 0. However, I can chose to make this a retry of 1000 (for example).

One can specify a timeout period (for example 60 seconds) with -s 60. Note, however, that this timeout period starts when the lockfile was last modified/created, and it forces the removal of the lockfile. This helps prevent zombie processes that were killed before they could remove their lockfile.

Be the first to like.

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*