Exclusive file lock in Perl

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.

Moving your apps to Amazon or Miscrosoft Clouds?

We can help you analyze your existing infrastructure, identify the cost savings we can achieve by migrating to a cloud provider. We can then execute end-to-end migration plan of your infrastructure and bringing down your TCO.

Cloud Computing

Ready for IPv6 Migration?

The Internet is running out of the equivalent of phone numbers - familiar problem, non-trivial solution.

The world has to move to IPv6, with its 128-bit addresses. But that's easier said than done.

IPv6 Migration

Are you fluent in "Linux"?

Learn Linux from a leading expert and quickly master you Linux skills.

Learn how to simplify your workflow and increase your productivity using tips and techniques of the pros.

Ideal training for Corporate IT Beginners and Advanced IT Admins alike.

Corporate Linux Training

Who's Online

We have 9 guests and no members online