Original address: HTTP://BLOGREAD.CN/IT/ARTICLE/743?F=WB
Some monitoring scripts are written in Perl and are scheduled for execution in Crontab. Sometimes it is found that a script runs too long and runs multiple instances at the same time, so it is necessary to add control to the script and run only one instance.
The simplest and most natural idea is to check and create an empty lock file in the script and delete it at the end of the script. Determine if the script is already running by judging whether the file exists. However, there is a bug, if the script is running abnormally terminated, the lock file is not deleted properly, it will cause the script can no longer run.
Empty lock file does not work, then consider adding a bit of content in the lock file, such as the PID number of the process, and then by checking whether the PID number of the process is still running, you can avoid the above bug. There are a lot of ready-made modules on CPAN to do the above functions, such as file::lockfile, File::P ID, Proc::P id::file , etc.
Here is an example of file::lockfile, which is very simple:
Here is the code snippet:
03 |
# lock file is located in the/tmp directory, named Test_file_lock.lck |
04 |
My $lockfile = file::lockfile->new (' Test_file_lock ', '/tmp '); |
05 |
# Check if the script is running and exit if it is already running |
06 |
if (My $pid = $lockfile->check) { |
07 |
Print "program was already running with PID: $pid"; |
By looking at the source code of FILE/LOCKFILE.PM, you can see whether the process recorded in the lock file has been run, simply by using the kill-0 $pid . So even without the above-mentioned modules, it is very easy to implement them.
Summary:
This method is often used in scripts to limit the single instance of the method, MySQL and other programs before each boot will also check the last legacy of the Mysql.pid file.
Another method: Lock the lock file and determine if there is a lock to ensure uniqueness.