in reply to (OT?) File Locking

You need to open that file for appending and lock it.

use Fcntl ':flock'; # ... code ... open FH, ">>$file" or die "Can't open $file: $!"; flock FH, LOCK_EX; # lock it # ... print() to file here flock FH, LOCK_UN; # not really necessary since close() # will unlock the file anyway close FH; # ... code ...


--perlplexer

Replies are listed 'Best First'.
Re: Re: (OT?) File Locking
by dws (Chancellor) on Apr 14, 2002 at 17:39 UTC
    Eeek! No! That code snippet is incomplete, and will eventually get people into trouble if they're trying to run on multiple platforms.

    If you intent to append to a file, you need to handle the small, but very real timing window between opening the file and acquiring the lock. Within that window, a different process can write the the file, leaving you with a bogus seek pointer. Best case, you'll lose the last record(s) written. Worse case, you'll write into the midst of them, leaving corrupted records.

    To mitigate the timing window, add the following line

    use Fcntl ':flock'; ... open FH, ">>$file" or die "Can't open $file: $!"; flock FH, LOCK_EX; # lock it +++ seek FH, 0, 2; # in case eof moved # ... print() to file here flock FH, LOCK_UN; close FH;
      Under UNIX, a file opened for appending automatically seeks to the end on every write(). No locking should be required, even with multiple processes appending, as long as every write is accomplished with a single system call (you can check that with strace/truss). If you take a look at the apache source, it doesn't lock the log file when it writes a message, and that's certainly a case where many processes are appending to the same file at once.

      In perl, you'll want to set $| on the log file handle, or the output buffers from the different processes will interleave. Or use syswrite.

      I don't know if this is true in Windows.

        I don't know if this [automatic seek to eof when writing a file opened for append] is true in Windows.

        It isn't. This is a frequent source of hard-to-track file corruption.