in reply to Re: Flocking and In-place editing
in thread Flocking and In-place editing

Great! Which filehandle do I lock?

Replies are listed 'Best First'.
Re: Re: Re: Flocking and In-place editing
by bobn (Chaplain) on Jan 27, 2004 at 03:00 UTC
    When I had the question of "which filehandle to flock", because I was reading a file, then writing the file, requiring me to close, then reopen it (in retrospect, I probably should have just used seek or some such), the solution was to flock a wholly separate file instead, eg.
    open LCK, "$file.lck"; flock(LCK, LOCK_EX); # operate on how ever many files here flock(LCK, LOCK_UN); close LCK;
    Of course, this only protects you from other instances of the same program, or other programs that use the same mechanism.

    --Bob Niederman, http://bob-n.com

    All code given here is UNTESTED unless otherwise stated.

      It's considered bad form to use LOCK_UN to release the lock on a filehandle - there is the potential for buffering to ruin your day if another process starts writing to the file before the current process closes the filehandle and flushes any data to disk.

      Closing the filehandle will ensure the data on disk is consistent, as buffered data will be flushed, and the flock is released automatically.

      If you're locking a semaphore file, as your example here suggests, it's somewhat of a non-issue, but it should be considered for other cases.


      If the information in this post is inaccurate, or just plain wrong, don't just downvote - please post explaining what's wrong.
      That way everyone learns.