Semaphores in libc

Luciano Rocha strange@nsk.no-ip.org
Mon Jan 4 12:13:00 GMT 2010


On Mon, Jan 04, 2010 at 12:42:43PM +0100, Petar Bogdanovic wrote:
> On Thu, Dec 31, 2009 at 04:31:33PM +0000, Luciano Rocha wrote:
> >
> > (...)
> > 
> > open("lockfile", O_CREAT | O_EXCL ...) also have problems, but the
> > manual page has a workaround:
> > 
> >        O_EXCL  is  only  supported  on NFS when using NFSv3 or later on
> >        kernel 2.6 or later.  In environments where NFS  O_EXCL  support
> >        is not provided, programs that rely on it for performing locking
> >        tasks will contain a race  condition.   Portable  programs  that
> >        want  to  perform atomic file locking using a lockfile, and need
> >        to avoid reliance on NFS support for O_EXCL, can create a unique
> >        file  on  the same file system (e.g., incorporating hostname and
> >        PID), and use link(2) to  make  a  link  to  the  lockfile.   If
> >        link(2)  returns  0,  the  lock  is  successful.  Otherwise, use
> >        stat(2) on the unique file  to  check  if  its  link  count  has
> >        increased to 2, in which case the lock is also successful.
> 
> I have a hard time understanding the last sentence.  What exactly is the
> purpose of stat(2) resp. checking the link count in that example?  Why
> would one want to issue stat(2) after a failed link(2) and why is the
> return of the former able to overturn the return of the latter?

Well... Let's see if I can make sense of it.

You do:
cli1# unique=$(hostname -s).$$
cli1# touch $unique
cli1# if ln $unique lockfile || [ $(stat -c %h $unique) -eq 2 ]; then
	echo got lock
fi

Ok. If link($unique, $lockfile) returns success, then your process got
the lock. If it returns failure, but stat($unique) returns the number of
hardlinks > 1, then the link actually succeeded, but the client NFS code
may have for some reason got confused. It could be that a previous lock
owner did an unlink($lockfile), but the client hasn't seen it yet, or
something. Really, I'm not aware of all POSIX deviations and
implications.

I got this from google:
http://opengroup.org/austin/mailarchives/austin-group-l/msg10343.html

-- 
lfr
0/0
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 198 bytes
Desc: not available
URL: <http://sourceware.org/pipermail/libc-help/attachments/20100104/c38a39ca/attachment.sig>


More information about the Libc-help mailing list