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.
- Proc A open FH for write (using > which clobbers the file contents)
- Proc B opens FH for reading (no lock attempt since it won't likely get an exclusive lock granted)
- Proc A locks FH
- Proc A works with FH
- Proc A closes FH
No need for a semaphore, just change the above a bit:
- Proc A opens FH for read/write (the file is not changed at all yet)
- Proc B opens FH for reading (and gets a shared lock)
- Proc A locks FH exclusively, after B has released it's shared lock
- Proc A works with FH
- Proc A closes FH
And yes, I need to update my tutorial. :)