in reply to Re: Re: correct usage of flock?
in thread correct usage of flock?

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.)

Replies are listed 'Best First'.
Re: Re: Re: Re: correct usage of flock?
by sierrathedog04 (Hermit) on Jun 06, 2001 at 19:31 UTC
    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.

      Except I have only one process, set to append, in a directory it has permission to create files in, so that should be OK, yes?
        It worked for me in Mandrake Linux 8. I took your script and moved the unlock to the very last statement. The single process was able to delete a file while it had an exclusive lock on it.
      You are not protected against the race condition I mentioned earlier. An unlink in Unix does not release the data from the file until the last file descriptor is closed. The second process will be able to read whatever information is in there (and write to it if it desires). Of course other processes wont know this since the file's name space entry is gone. The second process will continue under the assumption that it was accessing the locked file in a valid state (hey it was there when I opened it!).

      In some cases, perhaps the current one, this is ok in others it is not -- it depends on the assumptions being made after this section of code. In general if you are going to do this, it is a good idea to put a comment in your code that says you know about the possible race condition and it is ok.