in reply to RE: RE: RE: Flock Subroutine
in thread Flock Subroutine

Well, using anything incorrectly can lead to problems, but I still think a simple flock is best - just be careful about it.

> Here you should be able to see the race. Another process
> can get an exclusive lock on the FH during the read open
> (read-only opens don't generally get exclusive locks),
> and between the close of the read and open of the write.

I don't agree with this. First, if another process cannot get an exclusive lock while *any* other lock is on it. So if process A locks a file for reading (shared lock) and then process B tries to get an exclusive lock, process B cannot get the lock until *all* the locks are gone - shared and exclusive. In the second case, yes it's a problem, but that's a bad coding problem, not a problem with flock. The right way to do it of course is to open the file for read/write, get an exclusive lock, read in the file, rewind (usually), write to the file, and close it, releasing the exclusive lock.

  1. Proc A open FH for write (using > which clobbers the file contents)
  2. Proc B opens FH for reading (no lock attempt since it won't likely get an exclusive lock granted)
  3. Proc A locks FH
  4. Proc A works with FH
  5. Proc A closes FH

No need for a semaphore, just change the above a bit:

  1. Proc A opens FH for read/write (the file is not changed at all yet)
  2. Proc B opens FH for reading (and gets a shared lock)
  3. Proc A locks FH exclusively, after B has released it's shared lock
  4. Proc A works with FH
  5. Proc A closes FH

And yes, I need to update my tutorial. :)