This is the mail archive of the libc-help@sourceware.org mailing list for the glibc project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Semaphores in libc


On Mon, Jan 04, 2010 at 12:13:30PM +0000, Luciano Rocha wrote:
> 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.

Or another thread got the lock in the meantime.  It's not that much
about NFS as it is about the stat(2) call lacking value.  Whatever
stat(2) returns, you can't rely on it since other things can happen
between link(), stat() and your next step.

Why is the return value of link() not sufficient? (given a properly
functioning NFS-client)

		Petar Bogdanovic


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]