Perl flock - file locking with Perl

Perl flock FAQ: Can you show me how to lock a file with the Perl flock function?

Sure, here are a couple of quick file-locking examples with Perl and the Perl flock function.

Perl flock example #1

In the first Perl flock example I'll show how to lock a file, but I'll intentionally do it in a bad way, and lock a file for roughly 20 seconds while I write records to it and sleep in between the writes:

#!/usr/bin/perl

# program: perl-flock1.pl
# perl file locking example #1.
# loop for a while, keeping the file locked for roughly 20 seconds.

use Fcntl qw(:flock);

$file = 'test.dat';

# open the file
open (FILE, ">>", "$file") || die "problem opening $file\n";

# immediately lock the file
flock FILE, LOCK_EX;

# intentionally keep the lock on the file for ~20 seconds
$count = 0;
while ($count++ < 20)
{
  print FILE "count = $count\n";
  sleep 1;
}

# close the file, which also removes the lock
close (FILE);

Normally I'd say this example is bad coding, but I used this sample program to test how the file locking works. I'd start this program, then try to access the test.dat file using a Linux command like vi, cat, or more. If you're working on a Unix or Linux system, this can be a good Perl flock test program, so you can see how file locking works for yourself.

Perl flock example #2

In the next example I "fix" the problem with my Perl file locking program, and this time only lock the file right when I need to write to it. Except for the testing purpose I described in the previous paragraph, this is generally a much better approach to the file locking problem:

#!/usr/bin/perl

# program: perl-flock2.pl
# perl file-locking example #2.
# loop for a while, locking the file only when you need to write to the file.

use Fcntl qw(:flock);

$file = 'test.dat';

$count = 0;
while ($count++ < 20)
{
  open (FILE, ">>", "$file") || die "problem opening $file\n";
  # lock the file before i write to it
  flock FILE, LOCK_EX;
  print FILE "count = $count\n";
  close (FILE);
  sleep 1;
}

Do you see the difference in this code? Try saving both of these programs on your system, running them, and seeing the difference in accessing the test.dat file using external Linux programs (like cat and more).

If you're new to Perl, on Linux and Mac systems you can either run the programs like this:

perl perl-flock1.pl

or change the files to be executable and run them like this:

./perl-flock1.pl

Follow-up

Note that this type of lock is merely an advisory lock. I've read where this is described as a traffic light, or a stop sign. If other programs respect your lock everything will work as intended, but just as with a traffic light you don't have to stop, you just make a decision to stop.