Original article address:Http://blogread.cn/it/article/743? F = WB
I used Perl to write some monitoring scripts and put them in crontab for scheduling and execution. Sometimes you will find that a script runs for too long and starts multiple instances at the same time. Therefore, it is necessary to add control to the script to run only one instance.
The simplest and most natural idea is to check and create an empty lock file in the script and delete the file at the end of the script. Determine whether the script is running by checking whether the file exists. However, there is a bug in this case. If the lock file is not deleted normally during the script running process, the script will no longer run.
If the empty lock file does not work, consider adding a bit of content to the lock file, such as the PID Number of the process, and then check whether the process of the PID Number is still running, the above bug can be avoided. InCPANThere are many ready-made modules to complete the above functions, suchFile: lockfile,File: PID,Proc: PID: File.
The following is an example of file: lockfile, which is very simple:
Below isCodeFragment:
03 |
# The 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 whether the script is running. If the script is already running, exit. |
06 |
If ( My $ PID = $ Lockfile -> Check ){ |
07 |
Print "Program is already running with PID: $ PID" ; |
ViewSource codeWe can see that it is easy to determine whether the process recorded in the lock file is running.Kill-0 $ PID. Therefore, even if you do not use the above modules, it is very easy to implement by yourself.
Summary:
This method is often used in scripts to restrict a single instance, such as MySQL.ProgramBefore each startup, the mysql. PID file left over from the previous one will be checked.
Another method: Apply an exclusive lock to the lock file to determine whether a lock exists to ensure uniqueness..