Skip to content

Instantly share code, notes, and snippets.

@bsmr
Created February 17, 2016 15:41
Show Gist options
  • Save bsmr/c80b881c8f2d91bd3027 to your computer and use it in GitHub Desktop.
Save bsmr/c80b881c8f2d91bd3027 to your computer and use it in GitHub Desktop.
#!/bin/bash
# === global variables ================================================
LOCKBASE="/var/lock" # old
#LOCKBASE="/run/lock" # new
# === support functions ===============================================
# --- display usage information ---------------------------------------
action_usage() {
BN=$(basename $0)
cat <<EOF
usage: ${BN} [ no-lock-test | lock-test | help ]
EOF
}
# --- display extended usage information ------------------------------
action_help() {
cat <<EOF
To be done...
EOF
}
# --- a simple test ---------------------------------------------------
action_no_lock_test() {
SECS="$1"
if [ -z "${SECS}" ]
then
SECS="3"
fi
echo -n "TEST: about to sleep ${SECS}s..."
sleep "${SECS}"
echo " done."
}
# --- locking test ----------------------------------------------------
action_lock_test() {
LOCKFILE="$1"
CALLFUNC="$2"
shift
shift
if [ -z "${LOCKFILE}" ]
then
echo "Error: no lockfile name specified!" >&2
exit 1
fi
if [ -z "${CALLFUNC}" ]
then
echo "Error: no function to call specified!" >&2
exit 1
fi
# - - locking section - begin - - - - - - - - - - - - - - - - - - - - -
(
flock -x -n 234
if [ "$?" = "0" ]
then
# call the important function within the locked context
"${CALLFUNC}" $*
# clear lockfile, because we must have created it
rm "${LOCKFILE}"
# don't do any important stuff here
exit 0
else
echo "Error: Failed to acquire lock!" >&2
exit 1
fi
) 234>"${LOCKFILE}"
# - - locking section - end - - - - - - - - - - - - - - - - - - - - - -
}
# === main entry point ================================================
case $1 in
nt|no-lock-test)
shift
action_no_lock_test $1
;;
lt|lock-test)
shift
action_lock_test "${LOCKBASE}/script-lock-test.lck" "action_no_lock_test" "$1"
;;
help)
action_usage
action_help
;;
*)
action_usage
exit 1
;;
esac
exit 0
# --- end of file ---
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment