File Lock with Perl

I can't get Perl flock to work. I lock the file by checking the return result to make sure it is actually locked, and I can still open and write to it as if nothing was happening.

This 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 this script was sleeping, I can play with the same text file:

  #! / 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 trying to open a file and write to it without saying that it is locked?

+4
source share
3 answers

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

Also understand that the way you call flock() will block until it can get the lock. If you want a crash, you need to use the LOCK_NB flag.

 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() will not work on NFS

+11
source

I don't think flock does what you think it does. Locking a file does not prevent anyone from doing anything in the file, except for trying to get a lock in the same file.

From man 2 flock on my system:

flock (2) places only security locks; if there are appropriate permissions on the file, the process can ignore the use of flock (2) and perform I / O on the file.

+7
source

flock works with advisory locks. Among other things, this means that only other processes that try to execute flock the same file will understand that it is locked.

+4
source

Source: https://habr.com/ru/post/1343249/


All Articles