[comp.unix.questions] Does this lockfile method work?

mrapple@quack.sac.ca.us (Nick Sayer) (09/28/90)

void get_lock()
{
  sprintf(tmpname,"/tmp/t_%d",getpid());
  fp=fopen(tmpname,"w");
  fprintf(fp,"%d\n",getpid());
  fclose(fp);
  while(link(tmpname,"/tmp/LOCK")!=0) sleep(30);
  unlink(tmpname);
}

void release_lock()
{
  unlink("/tmp/LOCK");
}

Presuming for the moment that the possibility of an infinite wait
within the while loop won't occur, and release_lock() won't be
called unless the lock was previously aquired by this process,
does anyone see any exclusivity problems with this code?
In particular, is there any conceivable circumstance where
the link() function fails when multiple processes are trying
to link into the same destination? In this context, "fails" means
anything other than one process completing the link() successfully
and all the others getting EEXISTS.

-- 
Nick Sayer               |  Disclaimer:
N6QQQ [44.2.1.17 soon]   |    "Just because you're reading my post doesn't
mrapple@quack.sac.ca.us  |     mean we're gonna take long showers together."
209-952-5347 (Telebit)   |                      -- Gunnery Sgt. Thomas Highway

gwyn@smoke.BRL.MIL (Doug Gwyn) (09/30/90)

In article <a66fe0.6a9e@quack.sac.ca.us> mrapple@quack.sac.ca.us (Nick Sayer) writes:
>In particular, is there any conceivable circumstance where
>the link() function fails when multiple processes are trying
>to link into the same destination?

link() is atomic in this respect.  The only unexpected failure mode
I can think of is if there are already the maximum supported number
of (other) links to the inode.