help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] signal safe mutex in bash


From: Bob Proulx
Subject: Re: [Help-bash] signal safe mutex in bash
Date: Sun, 21 Apr 2013 17:50:23 -0600
User-agent: Mutt/1.5.21 (2010-09-15)

Peng Yu wrote:
> I see discussions on mutex based on lockfile (the following is for sh,
> but should be adapted for bash easily). But it is not safe with
> respect to signals like SIGINT SIGTERM. To do so, I know trap should
> be used. But I don't know the correct way. Could anybody let me the
> correct way to combine lockfile and trap to make the a mutex that is
> safe with respect to signals? Thanks.

Try this:

#!/bin/bash
LOCKFILE=$HOME/.myscript/lock
mkdir -p `dirname $LOCKFILE`

echo Waiting for lock $LOCKFILE...
if lockfile -1 $LOCKFILE
then
    trap "rm -f $LOCKFILE" EXIT

    # Do protected stuff here
    echo Doing protected stuff...
else
    echo "Failed to acquire lock!  lockfile(1) returned $?"
    exit 1
fi

After acquiring the lock then set an EXIT trap to remove it.  But only
if the current script acquired the lock.

Note that I changed the #! line to #!/bin/bash.  This doesn't work in
if /bin/sh is dash.  Dash also needs more setup.  Grr...  For /bin/sh
-> dash you must trap all of the signals that you might get sent in
addition to the EXIT trap.  Dash is clearly backwards there compared
to other shells.  Better to use bash or ksh or zsh in that case.  But
if you want to be portable to dash then you need something like this:

    trap "rm -f $LOCKFILE" EXIT
    trap "rm -f $LOCKFILE; trap - HUP; kill -HUP $$" HUP
    trap "rm -f $LOCKFILE; trap - INT; kill -INT $$" INT
    trap "rm -f $LOCKFILE; trap - QUIT; kill -QUIT $$" QUIT
    trap "rm -f $LOCKFILE; trap - TERM; kill -TERM $$" TERM
    trap "trap - PIPE; rm -f $LOCKFILE; kill -PIPE $$" PIPE

But I haven't quite convinced myself that is completely correct
everywhere yet.

Bob



reply via email to

[Prev in Thread] Current Thread [Next in Thread]