Created
February 28, 2012 15:16
-
-
Save mudrd8mz/1933037 to your computer and use it in GitHub Desktop.
Simple bash locking based on file existence
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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
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.