Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: File locking within zsh?



Lloyd Zusman <ljz@xxxxxxxxxx> writes:

> Do any of you know of any functions, primitives, tricks, hacks, or even
> outright abominations which will allow me to do cooperative file locking
> from within zsh?
> 
> I know that I can do this with a number of compiled executables, but I'm
> looking for a zsh-only solution.
> 
> Assuming some sort of zsh locking operator called "lock", consider
> this example (within a zsh script):
> 
>   lock -x -t 0 file  # for this example of a hypothetical operator, '-x'
>                      # means to wait until I get an exclusive lock, and
>                      # '-t 0' means no time out
>   print foo bar baz >>file
>   # do a whole lot of other stuff to "file"
>   unlock file # release the lock
> 
> In this example, any other zsh script which asks for an exclusive lock
> on "file" using this hypothetical "lock" operator will block until the
> "unlock" operator has been invoked.
> 
> Can this be done somehow in zsh, or do I have to rely on a compiled
> executable to accomplish this?

The usual way to lock within shell scripts is to use ln. This works on all
UNIX like systems because creating a hard link (with ln) is an atomic
operation which fails if the target already exists. Your example above can be
written like this:

    while ! ln file file.lock 2>/dev/null
    do
        sleep 1
    done
    # Lock obtained

    print foo bar baz >>file
    # do a whole lot of other stuff to "file"

    rm -f file.lock
    # Lock released

Wrapping this idiom into lock/unlock functions is left as an exercise for the
reader. :-)

-- 
tim writer <tim@xxxxxxxxxxx>                                  starnix inc.
647.722.5301                                      toronto, ontario, canada
http://www.starnix.com              professional linux services & products



Messages sorted by: Reverse Date, Date, Thread, Author