Skip to content

Instantly share code, notes, and snippets.

@TrevorS
Created July 16, 2014 19:59
Show Gist options
  • Save TrevorS/2d79eb748fe96ce3c1be to your computer and use it in GitHub Desktop.
Save TrevorS/2d79eb748fe96ce3c1be to your computer and use it in GitHub Desktop.
# dP
# 88
# 88 .dP .d8888b. dP dP dP dP dP .d8888b. dP dP
# 88888" 88ooood8 88 88 88 88 88 88' `88 88 88
# 88 `8b. 88. ... 88. .88 88.88b.88' 88. .88 88. .88
# dP `YP `88888P' `8888P88 8888P Y8P `88888P8 `8888P88
# .88 .88
# d8888P d8888P
#
# A simple lock file library.
# Version 0.0.1
#
# Return Code Explanation:
# 1: Your application was not able to acquire lock.
# 2: There was some other problem:
# a: Keyway could not create the lock directory.
# b: Keyway could not create or remove a lock.
#
# Example Usage:
#
# #!/bin/bash
# source keyway_lib.sh
#
# acquire_lock_for "maintenance"
# echo "execute critical section"
# release_lock_for "maintenance"
# Customize the location of your lock files for this application.
LOCK_DIR="locks"
acquire_lock_for() {
if not_locked $1; then
lock_log "Creating $1 lock."
touch "$LOCK_DIR/$1".lock
check_execution "acquire lock"
fi
}
release_lock_for() {
lock_log "Releasing $1 lock."
rm "$LOCK_DIR/$1".lock
check_execution "release lock"
}
not_locked() {
check_lock_dir
for lock in "$LOCK_DIR"/*.lock
do
if [ -f $lock ]; then
lock_log "Cannot run $1 -- application locked by $lock."
exit 1
fi
done
}
check_lock_dir() {
if [ ! -d $LOCK_DIR ]; then
lock_log "Creating lock directory: $LOCK_DIR"
mkdir -p $LOCK_DIR
check_execution "create lock directory"
fi
}
check_execution() {
if [ $? -ne 0 ]; then
lock_log "Could not $1, exiting."
exit 2
fi
}
lock_log() {
datetime=`date +"%Y-%m-%d %H:%M:%S"`
printf "$datetime - Keyway: $1\n"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment