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

Re: File locking within zsh?




----- Original Message ----- From: "Tim Writer" <tim@xxxxxxxxxxx>
To: "Lloyd Zusman" <ljz@xxxxxxxxxx>
Cc: <zsh-users@xxxxxxxxxx>
Sent: Tuesday, May 09, 2006 11:31 PM
Subject: 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. :-)


Is that better or worse, and why, than  umask 222 ; >file ?

http://www.unix.org.ua/orelly/unix/upt/ch45_36.htm


Brian K. White  --  brian@xxxxxxxxx  --  http://www.aljex.com/bkw/
+++++[>+++[>+++++>+++++++<<-]<-]>>+.>.+++++.+++++++.-.[>+<---]>++.
filePro  BBx    Linux  SCO  FreeBSD    #callahans  Satriani  Filk!



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