Un naufragio personal

File locking in Perl

File locking in Perl is done with the flock() function. It's portable among architectures, is advisory-only and locks full files.

It accepts two arguments: a file handle and an operation id. As expected, it allows only one writer or many simultaneous readers, with no wait. Locks are automatically released on closing. The usage is simple:

  1. Open the file (for reading or writing).
  2. Call flock() with the file handle, and a second argument of 1 (if reading) or 2 (if writing).
  3. Do whatever operations you do to the file.
  4. Close it.

And that's it. The magic numbers 1 and 2 can also be used as LOCK_* constants imported from the Flock module. The perldoc documentation is comprehensive, take a look at it.

Example reader:

 open F, 'index.db'; # open for reading
  1. lock file. If a writer has it locked, it will
  2. wait until released. Many readers will read the
  3. file simultaneously without blocking. flock F, 1;
 while (<F>) {
    # do things...
  1. lock is released close F;

And a writer:

 open F, '>index.db'; # open for writing
  1. lock file for writing. If there is another reader
  2. or writer using the lock, it will block until
  3. released. flock F, 2;
  1. file is now locked
  2. write stuff to the file...
  1. lock is released; any readers or writers waiting
  2. will unblock and go on with its business close F;

As these locking semantics are advisory-only, anyone can screw everything by writing without locking, so take care.