Peter Blair

Lock your files

Many people don’t do this, but whenever you’re working with files that can be touched by multiple processes, be sure to lock those files!

#!/usr/bin/perl -w
use strict;
use Fcntl qw(:DEFAULT :flock);
 
my $filename = '/tmp/test_lock_file';
 
open FD, "<$filename" or die( "Cannot open $filename: $!\n" );
 
unless( flock( FD, LOCK_EX | LOCK_NB ) ){
        local $| = 1;
        print "Waiting for lock on filename...";
        flock( FD, LOCK_SH ) or die( "Can't lock file: $!\n" );
        print "\n";
}
print "Received it! Hit Enter to release it...";
my $r = <>;
close( FD );

In window 1:

pblair@slowpoke:/tmp$ perl lock.pl
Cannot open /tmp/test_lock_file: No such file or directory
pblair@slowpoke:/tmp$ echo "blah" > /tmp/test_lock_file
pblair@slowpoke:/tmp$ perl lock.pl
Received it! Hit Enter to release it...

In window 2:

pblair@slowpoke:/tmp$ perl /tmp/lock.pl
Waiting for lock on filename...
Received it! Hit Enter to release it...


Categorised as: Perl


Comments are closed.

Get Adobe Flash playerPlugin by wpburn.com wordpress themes