in reply to correct usage of flock?

flock(FILE,2);
is an exclusive lock. That means that you can write or delete the file but others who use flock cannot. Therefore the correct approach is to make
flock(FILE,8)
the last line of your program. Then you are protected from race conditions.

I tried it out on my Linux box, and it works great. You can unlink a file while you have an exclusive lock on it, and indeed that is the best way to prevent anyone from writing to it before you are finished deleting it.

Replies are listed 'Best First'.
Re: Re: correct usage of flock?
by cLive ;-) (Prior) on Jun 06, 2001 at 06:53 UTC
    ?? So you're saying I can unlink that file whilst the FILE ilehandle is still open? Weird. I'll give it a go.

    cLive ;-)

      FWIW, this won't protect you from the case where two processes open the file at about the same time. The unlinked file won't be openable by other processes, since the namespace entry will be gone, but the two processes which already have it opened can continue to access it.

      The first process will do it's thing and then delete the file. The second process will grab the lock on the still opened file, and then process as if it had the lock -- it won't know the file has been unlinked. If you can live with this, that's fine. If you want "exactly once" semantics, it's not.

      FWIW, in general it's not a good idea to try to use an object's lock to synchronize the destruction of that object -- it is easy to overlook a race condition. You might get away with this in certain cases, but in general you'll rest easier if you use a different way. See one of the other methods described above (e.g. Ovid's 'sentinel', file renaming, etc.)

        Let's say that two processes which use flock both try and open the same file simultaneously. Only one of the processes will be able to lock it first. If that first process deletes the file and releases the lock then the second process will not be able to do anything to the deleted file. The second process will not read the nonexistent deleted file. It will not write it.

        So there is that protection against race conditions. Only one process will access the file at a time, which is the purpose of having an exclusive lock.