in reply to A flock()alypse now

Semaphore files have their uses:

Also, if you are going to just lock the file you want to modify instead of using a semaphore file, why are you opening the file, flock()ing the filehandle, then opening the file again?
Open the file with the permissions you'll need to perform the operations you've got planned, flock() it, do the operation, close the file.

Advisory locking never "plays well with others" if one of the those "others" ignores a lock, be it on a semaphore file, or the file itself. Generally, advisory locks are good enough.
I'd be surprised if there isn't a way of controlling other processes, and making sure that they go through filehandling/locking properly.

BazB

Update: Correction. Removed discussion on bad example (since author _knows_ it's bad :-)

Replies are listed 'Best First'.
Re: A flock()alypse now
by ferrency (Deacon) on Jul 02, 2002 at 18:42 UTC
    You are correct, and I won't argue that semaphores have no use. But, my point was to see if my technique actually works, for use when it's the appropriate solution.

    BazB wrote: Also, if you are going to just lock the file you want to modify instead of using a semaphore file, why are you opening the file, flock()ing the filehandle, closing the file (hence dropping the lock), then re-opening the file?

    In the sample code I provided which I didn't specifically label as broken, I don't close the $SEM filehandle after getting a lock on it, until after I open the same file in a different filehandle, process it, and close it. That would be Wrong :)

    The main use of a semaphore or second filehandle to lock a file (as opposed to the other uses you mentioned) is because you can't always open, flock, do the operations, and close the file in a straightforward way. For example, if you are doing a truncating open-for-write, you'll truncate the file before you have a lock on it. If you want to both read and write the file while it's locked, you have to either use a tricky read/write open and some seek's, or you have to open it, read it, close it, open it, then write it.

    Advisory locking never "plays well with others" if one of the those "others" ignores a lock, be it on a semaphore file, or the file itself.

    That's definitely true. But those aren't the cases I was talking about: I meant the cases where an existing code uses advisory locking in a known but unchangeable way, and you need to cooperate with it.

    Thank you for your insight,

    Alan