File Locking and Unlocking
######################## File Read-Lock Script ########################
#!/usr/bin/perl -w
use Fcntl ':flock'; # Get LOCK_SH, LOCK_EX, LOCK_UN, LOCK_NB constants.
open(F, "file") or die "Cannot open file!\n";
print "Cannot get read access!\n" if !flock(F, LOCK_SH | LOCK_NB);
sleep 20; # Keep script alive to maintain lock for a while!!
######################## File Write-Lock Script ########################
#!/usr/bin/perl -w
use Fcntl ':flock'; # Get LOCK_SH, LOCK_EX, LOCK_UN, LOCK_NB constants.
open(F, "file") or die "Cannot open file!\n";
print "Cannot get write access!\n" if !flock(F, LOCK_EX | LOCK_NB);
sleep 20;
################## Sample Sessions with Both Scripts ##################
$ lockr.pl&
[1] 2782792
$ lockw.pl
Cannot get write access! # Read lock prevents write lock!
$ lockw.pl&
[1] 2905742
$ lockr.pl
Cannot get read access! # Write lock prevents read lock!
$ lockr.pl&
[1] 2944515
$ lockr.pl
# No error message! Read lock does NOT prevent other read locks!
$ lockw.pl&
[1] 2737801
$ lockw.pl
Cannot get write access! # Write locks prevent other write locks!
#################### Guidelines for Using File Locking ##################
1. Remember to unlock files (with flock(HANDLE, LOCK_UN | LOCK_NB)) when
you no longer need a lock i.e., you have finished reading or writing
a file you have read- or write-locked.
2. Remember that you can still do any I/O operation on a locked file
because the locking is *advisory* locking -- the failure of flock
just reminds you to be nice and not write a file being read or
read a file being written.
3. Always use LOCK_NB to cause an immediate failure if a lock cannot
be obtained. Otherwise, the program waits INDEFINITELY until the
lock *can* be obtained. You may want this -- but not usually!
4. Always use locking in applications (such as TCP servers with multiple
child processes running around) where a good chance of simultaneous
file access exists.
5. File locking is irrespective of the file type so don't be confused
just because it is presented in the DB_File part of Perl Cookbook!!