File locking in Perl

Ángel Ortega

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

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

And a writer:

open F, '>index.db'; # open for writing

# lock file for writing. If there is another reader
# or writer using the lock, it will block until
# released.
flock F, 2;

# file is now locked
# write stuff to the file...
# lock is released; any readers or writers waiting
# 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.

Comments [Add new one]

None yet.