Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to get Perl's flock working

Tags:

file

locking

perl

I can't seem to make Perl's flock work. I'm locking a file, checking return valued to make sure it's actually locked, and I'm still able to open and write to it like nothing is the matter.

Here is how I lock the file

#!/usr/bin/perl -w

use strict;

use Fcntl ':flock';

$| = 1;

my $f = $ARGV[0];

open( my $fh, '>>', $f ) or die "Could not open '$f' - $!";
print "locking '$f'...";
flock($fh, LOCK_EX) or die "Could not lock '$f' - $!";
print "locked\n";

sleep 10;
print "waking up and unlocking\n";
close( $fh );

While that script is sleeping I can fiddle with the same text file from a different process

#!/usr/bin/perl -w

use strict;

my $f = $ARGV[0];

open( my $fh, '>>', $f ) or die "Could not open '$f' - $!";
print $fh "This line was appended to a locked file!\n";
close( $fh );

Why am I then able to open the file and write to it without being told that it's locked?

like image 479
ajwood Avatar asked Nov 28 '22 18:11

ajwood


2 Answers

flock() is an advisory lock. You have to have all your processes using flock()

Also realize that the way you are calling flock() it will block until it can get a lock. If you want a failure you have to use the LOCK_NB flag as well.

open(my $lf, ">>fileIWantToLockOn");
my $gotLock = flock($lf, LOCK_EX | LOCK_NB);

unless ($gotLock)
{
    print "Couldn't get lock. Exiting";
    exit 0;
}

EDIT: Also note that flock() won't work on NFS

like image 70
Brian Roach Avatar answered Dec 05 '22 09:12

Brian Roach


I don't think flock does what you think it does. Locking a file doesn't prevent anybody from doing anything to the file except trying to obtain a lock on the same file.

From man 2 flock on my system:

flock(2) places advisory locks only; given suitable permissions on a file, a process is free to ignore the use of flock(2) and perform I/O on the file.

like image 38
Greg Hewgill Avatar answered Dec 05 '22 08:12

Greg Hewgill