Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi again!

One more thing:
I've heard somewhere that using flock() on a file when -APPENDING- is unnecessary. Is that true, that flock() is needed only when writing to a file, and not needed to appending? It doesn't sound right, but I've read that somewhere!

Replies are listed 'Best First'.
Re: Re: flock
by btrott (Parson) on Apr 04, 2000 at 03:00 UTC
    That's not true--you should still use it when appending to a file. In fact, if you look at the flock docs, you'll notice that the example used is appending to a mailbox file. So use it.

    Furthermore, after you flock, you should seek to the end of the file, just in case another process appended to the file while you were waiting for the lock (but after you opened the file):

    open FH, ">>foo" or die "Can't open foo: $!"; flock FH, 2; seek FH, 0, 2;
      True, but from the flock manpage:
      If two separate processes open the same file for append, each process may write freely to the file without fear of destroying output being written by the other. The output from the two processes will be intermixed in the file in the order in which it is written.

      This is kinda discussed in some other thread, but basically if you are just appending a single line (e.g. some sort of log file) there is probably no strong compelling reason to lock the file. Locking does add a little overhead. If you are writing (i.e. changing any pre-existing data) definitely lock. If appending, almost always lock. :) From your example, I would definitely lock, but thought I would add this note anyway.