May times we require to check whether a process is running or not, may be for the purpose of maintaining a lock file for a process or for some other reason. Here today we'll discuss a technique in which we can do this checking provided the process/pid being checked is checked is run the same user as who is checking it or the checking script is running as root.
We'll use the kill function in Perl to achieve or goal, we'll send a SIGCHLD signal to the process if the function returns a non-zero value then we know the signals were successfully sent, i.e. the process is running. We send the SIGCHLD signal so as not to harm the process being checked.
# @file: check_process.pl - check whether a proccess is running or not.
my $pid = shift;
die "usage: check_process.pl pid\n" unless defined $pid;
print "Process ($pid) is ",(kill(SIGCHLD,$pid)!=0)?'running':'not running';
We sometimes would need to check that only one instance of a programs runs, like a program that runs from cron.It's be really helpful we can check whether the last launch of the program from the cron is still running. I hope someone will find this really useful.
my ($lock_file) = $0 =~ m!/([^/]+)$!; ## filename for the lock file, the program name should be unique
my $lock_file = "/tmp/$lock_file.pid"; ## tmp is usually writeable by anyone
my $pid = $$; ## pid of the current script
print "Already running ($file_pid)\n";
print FL "$pid";