[NBLUG/talk] Mutual exclusion in shell scripts?
Eric Eisenhart
eric at nblug.org
Sat Jan 20 18:38:23 PST 2007
On Sat, Jan 20, 2007 at 06:00:42PM -0800, Lincoln Peters wrote:
> On Saturday 20 January 2007 16:23, Eric Eisenhart wrote:
> > 1) procmail comes with "lockfile" that's designed to do what you want.
>
> Except I'm trying to use this as a manual filter in KMail.
lockfile is a separate program that's packaged with procmail because
procmail uses it. "man lockfile". Don't need to use procmail to use
lockfile.
The lockfile-using version of your program is:
lockfile /tmp/filter.lock
sa-learn $1 --no-sync
rm -f /tmp/filter.lock
(well, that's the default 8 second sleep; read the manpage if it must be 10.
There's also options for breaking a lock after a timeout, locking mailboxes,
changing to a conditional "if lockfile ...", etc...)
> > 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
>
> At first it looks more like an exercise in obfuscated code than anything else,
> but I think I see why this would work. I'll try it.
Heh.
Unless you use something like lockfile (or a snippet of perl code...), all
the solutions for locking in a shell script will be ugly. No direct access
to open with O_EXCL. I think you could do what open(2) suggests in shell,
but it's even uglier, especially since it's a technique looking for a do
while loop, not a while loop:
rm -f /tmp/filter.lock.$$
touch /tmp/filter.lock.$$
ln /tmp/filter.lock.$$ /tmp/filter.lock
until [ `stat -t /tmp/filter.lock.$$ | cut -d' ' -f9` == 2 ] ; do
sleep 10
ln /tmp/filter.lock.$$ /tmp/filter.lock
done
sa-learn $1 --no-sync
rm -f /tmp/filter.lock /tmp/filter.lock.$$
--
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