[NBLUG/talk] Mutual exclusion in shell scripts?

Eric Eisenhart eric at nblug.org
Sat Jan 20 16:23:44 PST 2007


On Sat, Jan 20, 2007 at 04:07:33PM -0800, Lincoln Peters wrote:
> I have the following shell script that I use to train spamassassin:
> 
> while [ -e /tmp/filter.lock ]
> do
> 	sleep 10
> done
> touch /tmp/filter.lock
> sa-learn $1 --no-sync
> rm -f /tmp/filter.lock

2 ways to avoid the race condition
1) procmail comes with "lockfile" that's designed to do what you want.

2) check for lock and create at once using a single atomic file operation:

while ! ln -s $$ /tmp/filter.lock 2> /dev/null
do
    sleep 10
done
sa-learn $1 --no-sync
rm -f /tmp/filter.lock


> Enough time passes between checking for /tmp/filter.lock and actually 
> setting /tmp/filter.lock that every instance of the script runs 
> simultaneously.  Is there a way to avoid that?
-- 
Eric Eisenhart
NBLUG Co-Founder
The North Bay Linux Users Group -- http://nblug.org/
eric at nblug.org, IRC: Freiheit at fn AIM: falschfreiheit
Jabber/XMPP/GTalk: freiheit at gmail.com



More information about the talk mailing list