Only one Perl instance – lock script

Use File::NFSLock to get an exclusive lock on the script itself:

use Fcntl qw(LOCK_EX LOCK_NB);
use File::NFSLock;

# Try to get an exclusive lock on myself.
my $lock = File::NFSLock->new($0, LOCK_EX|LOCK_NB);
die "$0 is already running!\n" unless $lock;


Alternatively use Sys::RunAlone near the top of your code.
 use Sys::RunAlone;
 # code of which there may only be on instance running on system

 use Sys::RunAlone silent => 1;
 # be silent if other running instance detected

 use Sys::RunAlone retry => 50;
 # retry execution 50 times with wait time of 1 second in between

 use Sys::RunAlone retry => '55,60';
 # retry execution 55 times with wait time of 60 seconds in between

 use Sys::RunAlone 'silent';
 # obsolete form of silent => 1
This entry was posted in Others and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *