René Nyffenegger's collection of things on the web
René Nyffenegger on Oracle - Most wanted - Feedback -
 

flock in perl

#!/usr/bin/perl

use Fcntl qw (:flock);

my $lock_file = 'dummy.lck';

open LOCKFILE, ">>$lock_file" or die "Cannot open $lock_file";
flock(LOCKFILE, LOCK_EX);
print "file locked, going to sleep\n";
sleep 10;
print "Woke up, releasing lock\n";
close LOCKFILE or die "Cannot close $lock_file";
flock calls are advisory. It won't affect any other script unless they use flock themselves as well. Here are five rules governing locks:
  • Locks don't affect anything except other locks. They don't stop anyone from opening, reading, writing, deleting, etc the file
  • There can only be one lock on an open file.
  • If someone holds a LOCK_EX lock, all attempts to get a lock fill wait (LOCK_EX meaning exclusive lock) until the other process releases the lock.
  • If someone holds a LOCK_SH lock, all attempts to get a LOCK_EX will fail, while other processes can aquire another LOCK_SH lock (LOCK_SH standing for shared lock)
  • The call to flock will not return until the lock can be aquired unless the lock is tried with LOCK_SH | LOCK_NB in which case the flock call will fail if another process has already aquired the lock.

Thanks

Thanks to Charles Selig who reported a typo.