[RndTbl] race conditions?
Sean Cody
sean at tinfoilhat.ca
Thu Jul 12 21:18:14 CDT 2012
On 2012-07-12, at 9:04 PM, Sean Walberg wrote:
> I'd use a lock file just to be safe. Depending on how "restart-daemon" works you might end up with a race condition inside there, resulting in no daemon getting run until the next pass.
>
> The easiest way would be
>
> lock="/var/run/mylock"
> if [ -f $lock ]; then exit 1; else touch $lock; fi
> #do your magic
> rm $lock
>
> There are other utilities like flock and lockfile if you are really concerned about re-entrancy, and depending on the user you run this script as, you may want to put $lock out of a normal user's reach. But to protect something running from cron, this will be more than enough.
>
> Sean
Sean beat me to it! :)
The only thing I have to add is that (if you are using bash and a recent release) that you trap as many signals as possible (post lock file creation) and in that trap remove the lock file. Otherwise you are in a fun state where everything looks alright but isn't running because the lock didn't get removed for a random number of reasons.
ie.
trap "rm $lock" SIGINT SIGHUP SIGTERM SIGALRM
eg 2.
#!/bin/bash
LOCKFILE=/var/run/mylock
[ -f $LOCKFILE ] && exit 0
trap "{ rm -f $LOCKFILE ; exit 255; }" SIGINT SIGHUP SIGTERM SIGALRM EXIT
touch $LOCKFILE
# do your magic here
exit 0 # note this will call the trap. :)
--
Sean
More information about the Roundtable
mailing list