Skip to content

Instantly share code, notes, and snippets.

@csw
Last active December 23, 2015 11:59
Show Gist options
  • Save csw/6632297 to your computer and use it in GitHub Desktop.
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)
#!/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
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