This is a fragile mechanism. I prefer to use real file locks, so when the process that owns them dies, the O/S will release the lock automatically. Easy to do in perl (using the flock function), but i don't know if it's possible in Bash.
More to the point, i suppose you could use the lockfile itself to hold the PID of the script holding the lock, right?
(I don't do shell scripting much... i think the code below is mostly right, but use at your own risk. There are race conditions.)
while [[ lockfile -! -r 0 lock.file ]]
do
kill -0 `cat lock.file`
if [[ $? -ne 0 ]]
then
# process doesn't exist anymore
echo $$ >lock.file
# do something important
rm -f lock.file
break
fi
sleep 5
done
Or, how about this:
while [[ true ]]
do
if [[ ! -e pid.file ]]
then
echo $$ > pid.file
else
if [[ kill -0 `cat pid.file`]]
then
# owner process exists
sleep 30
else
# process gone, take ownership
echo $$ > pid.file
# ### DO SOMETHING IMPORTANT HERE ###
rm -f pid.file
break
fi
fi
done
I like the second one better. It's still far from perfect (lots of race conditions), but it might work if there aren't too many processes fighting for the lock. Also, the sleep 30 should include some randomness in it, if possible (the length of the sleep should have a random component).
But see here, it looks like you can use flock with some versions of the shell. This would be similar to what i do in perl, and it would be safer than the althernatives i can think of.