NFS File Locking
1 direct reply — Read more / Contribute
|
by jbw8387
on Apr 08, 2026 at 09:02
|
I have an NFS file system mounted on many machines. I am attempting to use file locking to get exclusive access by one system to a file.
The critical code section shown here:
# loop through file names looking for one we can lock
open ( my $file_handle, '+<', $file_name ) or next;
if ( !flock( $file_handle, LOCK_EX | LOCK_NB ) ) {
close( $file_handle );
next;
}
# do some work here based on the file contents
unlink $file_name;
close( $file_handle );
This almost always works, but occasionally there is a failure where two machines get a lock on the same file. It appears there is a race between unlinking (deleting) the file and releasing the lock. It seems like there is a small window where the lock is actually released before the file is deleted allowing another machine to lock and read the file before it is deleted.
I am wondering if this is a known problem and if there is a preferred way to work around this.
|