Many times we need to lock a file for an exclusive lock. e.g you may want to prevent running script simultaneously by different users. Below is an example how to lock a file.
#!/usr/bin/perl
# locktest - file lock example
use strict;
use warnings;
use diagnostics;
use FileHandle;
use Fcntl qw(:flock);
open SELF, ">> $0" or die("Unable to lock the file");
flock(SELF, LOCK_EX) or die "Cannot lock - $!";
# Exclusive lock print "Locking...\n";
sleep(60); close SELF;
print "Unlocked...\n";
exit 0;
Now, log in and run “locktest”. At the same time, log in as a different user account and run the same script. You will see that it will not lock until the other script finishes.
We have 9 guests and no members online