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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment