Last active
December 23, 2015 11:59
-
-
Save csw/6632297 to your computer and use it in GitHub Desktop.
Simple, general pid lock file mechanism for ksh, for cron jobs (esp. on Solaris)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/ksh | |
function grab_lock { | |
pid_lock $lockfile || exit 1 | |
if [ ! -e $lockfile ]; then | |
print -u 2 "Lock file $lockfile should exist!" | |
exit 1 | |
fi | |
} | |
function run_program { | |
if [ -e $HOME/.profile ]; then | |
. $HOME/.profile | |
fi | |
print -u 2 "$$: executing: $run_cmd" | |
exec $run_cmd | |
} | |
function release_lock { | |
print -u 2 "$$: completed, releasing lock." | |
rm $lockfile | |
} | |
. `dirname $0`/lock.ksh | |
basedir=`dirname $0`/../.. | |
config=$1 | |
if [ "$config" == "" ]; then | |
print -u 2 "Usage: $0 <config>" | |
exit 2 | |
fi | |
if [ ! -e "$config" ]; then | |
print -u 2 "Error: config file $config does not exist!" | |
exit 2 | |
fi | |
# read the config file | |
. $config | |
## check settings | |
if ! (test "$lockfile" && test "$logfile" && test "$run_cmd"); then | |
print -u 2 "Error: config file $config must specify lockfile, logfile, and run_cmd!" | |
exit 2 | |
fi | |
redirect 2>>$logfile | |
grab_lock | |
(run_program) | |
release_lock | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function pid_lock { | |
typeset lockfile | |
lockfile=$1 | |
if [ -e $lockfile ]; then | |
lock_pid=`cat $lockfile` | |
if kill -0 $lock_pid 2>/dev/null; then | |
# still running | |
print -u 2 "$$: PID $lock_pid still running, exiting!" | |
return 1 | |
else | |
# stale lock | |
print -u 2 "$$: Stale lock from PID $lock_pid, taking lock." | |
fi | |
fi | |
if print "$$" > $lockfile; then | |
return 0 | |
else | |
print -u 2 "$$: Failed to write lock file $lockfile!" | |
return 1 | |
fi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment