#!/bin/sh ############################################################################### # # # Helper for periodically executed shell scripts (e.g. from cron(8)), # where you want to be absolutely sure that only one copy of script # is running at time. It also tries to handle common signals. Although, # can't handle cases where machine is crashed or when scripts exits before # "__unlock" or without calling it. Be aware of that, if until lock file # is not deleted, your script WILL NOT run. # # # Written by Sulev-Madis Silber # Last modified Tue Oct 24 18:37:18 2006 # # ############################################################################### # # Example #1 ############### # # #!/bin/sh # # # Source in our helper # . THIS_FILE # # # # Optionally, set lockfile, instead of default "$0.lock" # __lockfile my.lock # # # # Lock script # __lock # # # It surely runs long, but safely # sleep 3600 # # # Unlock script # __unlock # # # Example #2 ############### # # #!/bin/sh # # # Source in our helper # . THIS_FILE # # # # It surely runs long, but safely # __run sleep 3600 # # ############################################################################### __LOCKFILE="$0.lock" __lockfile() { if [ "$1" ] then __LOCKFILE=$1 else echo 'Locker: fatal error' >&2 exit 1 fi } __lock() { if [ -f "$__LOCKFILE" ] then #echo "$0 (PID $$) aborted, last session is still running" >&2 exit 1 fi touch "$__LOCKFILE" } __unlock() { rm -f "$__LOCKFILE" } __run() { __lock $* __unlock } trap '__unlock; exit' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 24 25 26 27 30 31