http://qs1969.pair.com?node_id=14139


in reply to File Locking

woops, went beyond what I could, I will put this in a few replies... change of having corrupt data.

One good strategy is to move the locking away from the data file altogether by using a semaphore file. Consider the following:

use strict;
use Fcntl qw(:flock);

my $file = 'data.file';
my $SEMAPHORE = "$file.lck";

open(S, ">$SEMAPHORE) || die "Foo ($!)";
flock(S, LOCK_EX);
open(FH, "+<$file") || die "Foofoo ($!)";
# Muck with file
close FH;
close S;

This solves a few problems. First, this allows you to ensure you get a lock when you open a file only for reading. Some systems will not give an exclusive lock on files (which is why you open the semaphore file for write) which were opened only for write only. This gets around that issue. And, by removing the issue of locking completely off the actual data file, you can use one semaphore file to lock multiple files, or directories. And, by removing the locking from the data file you reduce the risk of saying one morning "My hit counter reset itself!".