getpid() or something similar

Keith Wansbrough
Thu, 22 May 2003 16:59:05 +0100

> mandatory locks arn't needed. (and they are a common extension to the
> fcntl(2) locking mechanism anyway, at least I do not know of a system
> which doesn't support them)
> open(..., O_RDWR | O_CREAT | O_EXCL, 0600);
> is what you want, (wrapped in haskell of course) it will create the file
> if it doesnt exit (O_CREAT) but if it already does exist then it will
> return an error (EEXIST). this check is done ATOMICALLY, meaning there
> is no race condition.

Not so; on NFS, the implementation is *not* atomic, and the race
remains.  See the Linux open(2) man page, for example:

      O_EXCL When  used with O_CREAT, if the file already exists
              it is an error and the open will fail. In this con­
              text,  a  symbolic link exists, regardless of where
              its points to.  O_EXCL is broken on NFS  file  sys­
              tems,  programs  which  rely  on  it for performing
              locking tasks will contain a race  condition.   The
              solution for performing atomic file locking using a
              lockfile is to create a unique file on the same  fs
              (e.g., incorporating hostname and pid), use link(2)
              to make a link to the lockfile. If  link()  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 suc­

The suggested solution still requires a unique filename, so you still
need to use the complicated filename-generation technique, and you
still can't proof yourself against a hostile user guessing the right
name to use at the right moment.

Summary: NFS is broken, but it's too late now to fix it.

--KW 8-)