Use file:: lockfile in Perl to ensure that the script runs in a single instance


Some monitoring scripts are written in Perl, and are executed in crontab. Sometimes it is found that a script runs too long and multiple instances run at the same time. Therefore, it is necessary to add control to the script and run only one instance.

The simplest and natural idea is to check and create an empty lock file in the script and delete it at the end of the script. Judge whether the script has been run by judging whether the file exists. However, there is a bug in doing so. If the script terminates abnormally and the lock file is not deleted normally, the script will no longer run.

If an empty lock file does not work, consider adding some content to the lock file, such as the PID number of the process, and then you can avoid the above BUG by checking whether the process with the PID number is still running. There are many ready-made modules on cpan that can complete the above functions, such as file:: lockfile, file:: PID, proc:: PID:: file, etc.

The following is an example of file:: lockfile, which is very simple:

Here is a code snippet:


Copy codeThe code is as follows:

#!/usr/bin/perl -w
#The lock file is located in the / tmp directory and is called test_ file_ lock. lck
my $lockfile= File::Lockfile->new(‘test_file_lock’,’/tmp’);
#Check whether the script has been run, and exit if it has been run
if ( my $pid= $lockfile->check ) {
  print”program is already running with PID: $pid”;
#Update lock file
#Script logic
#Delete lock file


By viewing file / lockfile From the source code of PM, you can judge whether the process recorded in the lock file has been running. You can simply kill – 0 $PID. Therefore, even without the above modules, it is very easy to implement by yourself.


This method is often used in scripts to limit single instances. MySQL and other programs will also check the last remaining MySQL before each startup PID file.

Another method: add an exclusive lock to the lock file to determine whether there is a lock to ensure uniqueness.

Recommended Today

Hive Foundation

1、 Hive basic concepts Hive is a data warehouse tool based on Hadoop. It can map structured data files into a table and provide SQL like query functions. The essence is:Convert HQL into MapReduce program flow chart Architecture Principle Architecture diagram User interface (client):cli (hive shell), jdbc/odbc (Java access hive), webui (browser access hive) Metadata: […]