in reply to File Locking
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!".