Re: Making sure one and only one copy of a process is always running

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Sun, Nov 02, 2003 at 11:11:14AM -0600, Rodolfo J. Paiz wrote:
> I am trying to create a job which will run for a long time, so I need to 
> make sure that it:
> 
>    * starts up automatically
> 
>    * is always running
> 
>    * checks to see if it is running and restarts itself if the previous 
>      instance died
> 
>    * never runs two copies of itself

You've a couple of solutions.  One is to run it from /etc/inittab with the
respawn option.

The second is to use the PID in a run file.  If it can be run with
permissions to modify files in /var/run, that's the standard location.
Otherwise, you'll have to create a location it knows about.

>From this point on, I'll assume you're running a script; the algorithm
is the same from a program.

To save the PID, just do something like "echo $$ >$PID_FILE", where
PID_FILE is set to the filename of your lock directory and file.
However, there are a couple of tricks to avoid race conditions and to
allow restarts.

First, instead of overwriting the file, append to it--
"echo $$ >>$PID_FILE".  Then immediately read the first line of the
file; if the PID doesn't match your PID, you know to check if another
instantiation of yourself is still alive
(CKPID=`head -n 1 $PID_FILE`;kill -0 $CKPID and check the return code).

This guarantees that if $PID_FILE isn't there, your PID immediately is
in place to lock yourself in as the running process.  Then, if it turns
out another IS running, you can just quietly die.  Note that the file will
continue to grow by the size of a PID; but as this is only 3-6 characters,
no big deal even if the process doesn't get shut down for a year.  (Moreover,
if you see a lot of PIDs in the file, it tells you that your startup
algorithm is running too freely.)

Another trick is that you can stash the kill and startup command
options in the PID file just after the PID.  This still works with the
above scheme, and allows you to keep conditional options that vary on a
per-execution basis in a known location, for the current instantiation,
for shutdown and/or restart programs (or for the same program restarting
itself.)  Not common, but useful when necesary.

Cheers,
-- 
	Dave Ihnat
	ignatz@xxxxxxxxxx


-- 
redhat-list mailing list
unsubscribe mailto:redhat-list-request@xxxxxxxxxx?subject=unsubscribe
https://www.redhat.com/mailman/listinfo/redhat-list

[Index of Archives]     [CentOS]     [Kernel Development]     [PAM]     [Fedora Users]     [Red Hat Development]     [Big List of Linux Books]     [Linux Admin]     [Gimp]     [Asterisk PBX]     [Yosemite News]     [Red Hat Crash Utility]


  Powered by Linux