Here are a couple of quick file-locking examples with Perl and the flock function.
In the first example I do something intentionally dumb, and lock a file for roughly 20 seconds while I write records to it and sleep in between the writes:
#!/usr/bin/perl
# program: filelocker1.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 and lock the file
open (FILE, ">>", "$file") || die "problem opening $file\n";
flock FILE, LOCK_EX;
$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.
A second example
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:
#!/usr/bin/perl
# program: filelocker2.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";
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 filelocker1.pl
or change the files to be executable and run them like this:
./filelocker1.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.