In said:
Greetings,
I want to check whether a particular script (say
test.txt) is already running in background or not?
If it exists then I want to exit the code else proceed further.
I am new to perl and have done this in shell scripting but not able to
find the equivalent in perl
-- unix shell script
if [[ `ps -ef | grep $script_name | grep -vcE "grep|vi|cat|more|tail|
head" ` > 1 ]]; then
echo " $script_name script is currently running on `hostname`"
exit
fi
Depends on the platform, my personal favorite is to create a broken
symlink containing the process ID, something like this:
If you know the process ID, you can use kill() to determine if it's running.
If you use "ps | grep" you'll run the risk of accidently killing a process with
the same name.
# ------------- lock_process --------------------
#
# Attempt to create a symlink, will fail if such a symlink already exists.
# we use this failure.
#
while(! symlink($$,$FLAG)){
my $pid = readlink($FLAG);
#
# This is the "guts" of it, kill with a signal of 0 only reports
# whether or not a given process ID exists.
#
if(! kill(0,$pid)){
warn "Stale PID $pid";
unlink($FLAG); # There is a slight race condition here, however,
} # We should normally never be here anyway.
sleep(1); # Pause, count how many loops for a timeout, etc..
}
#
# At the end of our script, we need to do this. However, a kill -9 will blow us
# away and we'll end up with a stale lockfile. The above code (with the race condition..)
# is an attempt at recovering from a former "blown away" process.
#
END {
unlink($FLAG);
}
#------------------------------------------------
I don't know why I perfer to cram the info into a symlink, guess it's a habit. Most
people seem to use pid files. Far as I know, both are equally valid methods, symlinks
aren't portable though. You do need something that is "atomic" for the flag creation,
open(FH,">pidfile") is not a good choice since it'll happily clobber a brother who
managed to squeak in on a time slice.
Also, if this is to run on multiple machines (shared filesystem) there is a chance
that kill won't work. In that situation, you should put the current hostname into
the link and match it against the host that's trying to clear the lockfile.
Jamie