Skip to content

Instantly share code, notes, and snippets.

@mudrd8mz
Created February 28, 2012 15:16
Show Gist options
  • Save mudrd8mz/1933037 to your computer and use it in GitHub Desktop.
Save mudrd8mz/1933037 to your computer and use it in GitHub Desktop.
Simple bash locking based on file existence
#!/bin/bash
# Simple locking mechanism based on file existence
LOCK_ERR_ARGS=64
LOCK_EXISTS=1
LOCK_MISSING=2
LOCK_ROOT=/var/run/amos
#
# Helper function to report an error
# param: message to display
#
function lock_error() {
echo "$@" > /dev/stderr
}
#
# Acquire a lock or die
# param: lock name
#
function lock_get() {
if [[ $# -lt 1 ]]; then
lock_error "Missing lock name"
exit $LOCK_ERR_ARGS
fi
if [[ -f $LOCK_ROOT/$1.lock ]]; then
lock_error "Lock $1 exists - unable to acquire"
exit $LOCK_EXISTS
fi
date > $LOCK_ROOT/$1.lock
}
#
# Release an existing lock or die
# param: lock name
#
function lock_release() {
if [[ $# -lt 1 ]]; then
lock_error "Missing lock name"
exit $LOCK_ERR_ARGS
fi
if [[ ! -f $LOCK_ROOT/$1.lock ]]; then
lock_error "Non-existing lock $1 - unable to release"
exit $LOCK_MISSING
fi
unlink $LOCK_ROOT/$1.lock
}
#
# Confirm an existing lock or die
# param: lock name
#
function lock_confirm() {
if [[ $# -lt 1 ]]; then
lock_error "Missing lock name"
exit $LOCK_ERR_ARGS
fi
if [[ ! -f $LOCK_ROOT/$1.lock ]]; then
lock_error "Non-existing lock $1 - unable to confirm"
exit $LOCK_MISSING
fi
date >> $LOCK_ROOT/$1.lock
}
#!/bin/bash
source /path/to/locklib.sh
lock_get jobname
echo "Executing the job!"
lock_release jobname
@uhoreg
Copy link

uhoreg commented Feb 29, 2012

The problem with this is that you have a race condition -- if you have two processes trying to get a lock, and they both run the "if [[ -f $LOCK_ROOT/$1.lock ]];" check before the other creates the lock file, then both processes will get the lock.

@mudrd8mz
Copy link
Author

mudrd8mz commented Mar 1, 2012

Yes. Everybody here and there comments and repeats this race condition like a mantra. But honestly, this is expected just to guard cron jobs so that the same line from crontab is not executed until its previous incarnation finishes. If there are two threads at the machine trying to execute cronjobs at the same time, the server is in much bigger trouble anyway.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment