Avoid script running multiple times by file lock
Sometimes we need a single instance of a script to run at a time. Meaning, the script itself should detects whether any instances of himself are still running and act accordingly.
When multiple instances of one script running, it’s easy to cause problems. I’ve ever seen that about 350 instances of a status checking script running there without doing anything, but eat lots of system resource. I create a simple blog post on my website which show some implementation examples by Perl, Python and Shell. It's simple to implement it in Bash Shell: Code:
# This is to examine whether the lockfile existed An updated version: Code:
# Create the lock file |
ps -ef | grep -q "myscriptname" | grep -v grep && exit
|
Quote:
|
One of my friends gave me another solution like this:
Code:
lock_on() |
Slight amendment to post #2:
-q = quiet, but also "Exit immediately with zero status if any match is found, even if an error was detected." http://linux.die.net/man/1/grep Personally I'd want to know if an error occurred. The '&& exit' is also redundant. Otherwise, yes, use ps. The problem with lockfiles is that if a program crashes, the lockfile is not removed(!). Check for the program actually running, imho. |
Another thing to consider is:
If the script that you are checking for is the script you are running from, check the process id and compare it against the value of $$ |
Quote:
Code:
fuser "$f" &> /dev/null Code:
eval "exec $freefd< \"$f\"" Co-operative locking between asynchronous processes requires an atomic operation, that is an operation which is guaranteed not to be interrupted between initiation and completion. AFAIK there are only two such filesystem-related primitives: ln and mkdir. The existence of procmail's "lockfile" command saves shellscript coders a lot of work in this area! It includes a -l timeout function to set the maximum age of a lockfile -- useful if you can be sure of the maximum time the lock must be held for. For debugging and sysadmin it is helpful if the process that created a log file writes its ID info into the lockfile. I don't think procmail's lockfile supports that. |
All times are GMT -5. The time now is 07:24 AM. |