[OpenIndiana-discuss] shell script mutex locking or process signaling

Aneurin Price aneurin.price at gmail.com
Thu May 30 16:13:48 UTC 2013


On 30 May 2013 15:29, Laurent Blume <laurent+oi at elanor.org> wrote:
> On 30/05/13 16:15, Edward Ned Harvey (openindiana) wrote:
> <snip>
>
>> I see there are a bunch of C constructs available ... mutex_init,
>> etc.  Surely there must be a wrapper application around this kind of
>> thing, right?
>
>
> I spent some time looking for a lock in shell some time ago. The overall
> conclusion was that the only atomic operation in pure shell is mkdir.

I don't know about pure/POSIX shell, but at least bash and ksh support
noclobber, which should do the trick. I've been using the following
idiom for some time without problems:

#!/bin/bash

GLOBAL_LOCKFILE=/var/run/whatever.lock

function get_lock {
    ( set -o noclobber; echo "$$" > "$1") 2> /dev/null
    return $?
}

function have_lock {
    [ -f $1 ] && [ $(cat $1) = $$ ]
    return $?
}

function release_lock {
    if have_lock $1; then
        rm -f $1
    fi
    return 0
}

function cleanup {
    # Whatever cleanup required
    release_lock $GLOBAL_LOCKFILE
    return $1
}

trap 'cleanup $?' INT TERM EXIT
if get_lock $GLOBAL_LOCKFILE; then
    # Do stuff
fi

NB: I hacked that out of a larger and more complex script; I hope I've
selected the relevant bits, but I haven't actually tested it.
(This locking looks sane to me, and it's been working in practice for
months, but if anyone does see any obvious blunders do point them
out.)



More information about the OpenIndiana-discuss mailing list