Skip to content

Instantly share code, notes, and snippets.

@hgezim
Forked from esoupy/LockFile.sh
Created January 7, 2013 20:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hgezim/4478170 to your computer and use it in GitHub Desktop.
Save hgezim/4478170 to your computer and use it in GitHub Desktop.
#!/bin/bash
## LockFile function ##
# example:
# main() {
# LockFile create
# RunScriptStuff
# LockFile remove
# }
#Globals
Prog=$(basename $0)
Pid=$$
PidFile=/tmp/$Prog.pid
LockFile() {
## Manage LockFile ##
# Usage: LockFile [ create | remove | test ] #
_LockCmd=$1
rcode=0
case $_LockCmd in
test) [ -f $PidFile ] && _LockPid=$(cat $PidFile) && rcode=1
[ $_LockPid ] && [ -d /proc/$_LockPid ] && rcode=2
[ $rcode -eq 1 ] && echo "Stale Lockfile (pid:$_LockPid)"
[ $rcode -eq 2 ] && echo "Active Lockfile (pid:$_LockPid)"
return $rcode
;;
remove) [ -f $PidFile ] && rm -f $PidFile
;;
create) LockFile test
RetVal=$?
[ $RetVal -eq 2 ] && echo "Error: $Prog already running." && exit 1
if [ $RetVal -eq 1 ]; then
echo "Info: Removing stale lockfile."
LockFile remove
fi
touch $PidFile
echo $Pid > $PidFile
;;
*) echo "[Internal Error] $FUNCNAME: unknown argument '$_LockCmd'."
;;
esac
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment