Skip to content

Instantly share code, notes, and snippets.

@jianingy
Last active August 29, 2015 14:20
Show Gist options
  • Save jianingy/6be315bfcbb831cab6ea to your computer and use it in GitHub Desktop.
Save jianingy/6be315bfcbb831cab6ea to your computer and use it in GitHub Desktop.
Prevent process from running when lock file exists.
#!/bin/bash
# filename : with_local.sh
# created at : 2015-05-04 11:28:24
# author : Jianing Yang <jianingy.yang@gmail.com>
if [ "$#" -lt 2 ]; then
echo "Usage: $(basename $0) lockfile command"
echo "Prevent process from running when lock file exists."
echo
echo "Example:"
echo " with_lock.sh sleep.lock sleep 10"
fi
lockfile="$1"
shift
# test lock
if ! ln -s "$$" "$lockfile" &>/dev/null; then
pid="$(readlink $lockfile)"
echo "another process (pid=$(readlink $lockfile)) is running."
if [ ! -d "/proc/$pid" ]; then
echo "this is a dangling lock file. i'll remove it"
rm -f $lockfile
# try again
exec $0 $lockfile $@
fi
exit 111
fi
# run the program
$@
# remove lock
rm -f $lockfile
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment