tags:

views:

634

answers:

5

Hello,

So I'm trying to set up a cron job as a sort of watchdog for a daemon that I've created. If the daemon errors out and fails, I want the cron job to periodically restart it... I'm not sure how possible this is, but I read through a couple of cron tutorials and couldn't find anything that would do what I'm looking for...

My daemon gets started from a shell script, so I'm really just looking for a way to run a cron job ONLY if the previous run of that job isn't still running.

I found this post, which did provide a solution for what I'm trying to do using lock files, not I'm not sure if there is a better way to do it... http://stackoverflow.com/questions/851872/does-a-cron-job-kill-last-cron-execution

Thanks for your help

+4  A: 

Don't try to do it via cron. Have cron run a script no matter what, and then have the script decide if the program is running and start it if necessary (note you can use Ruby or Python or your favorite scripting language to do this)

Earlz
Figured this was where I had to go, thanks, +1, but I think I'll use the other guys' script, so he gets the correct answer... sorry
LorenVS
The classic way is to read a PID file that the service creates when it starts, check if the process with that PID is still running, and restart if not.
tvanfosson
+4  A: 

I do this for a print spooler program that I wrote, it's just a shell script:

#!/bin/sh
if ps -ef | grep -v grep | grep doctype.php ; then
        exit 0
else
        /home/user/bin/doctype.php >> /home/user/bin/spooler.log &
        #mailing program
        /home/user/bin/simplemail.php "Print spooler was not running...  Restarted." 
        exit 0
fi

It runs every two minutes and is quite effective. I have it email me with special information if for some reason the process is not running.

jjclarkson
Thanks, I'll test it out and see how it goes.
LorenVS
Works great... Thanks
LorenVS
+3  A: 

As a follow up to Earlz answer, you need a wrapper script that creates a $PID.running file when it starts, and delete when it ends. The wrapper script calls the script you wish to run. The wrapper is necessary in case the target script fails or errors out, the pid file gets deleted..

Byron Whitlock
Oh cool... I never thought about using a wrapper... I couldn't figure out a way to do it using lock files because I couldn't guarantee that the file would get deleted if the daemon errored out... A wrapper would work perfectly, I'm going to give jjclarkson's solution a shot, but I'll do this if that doesn't work...
LorenVS
A: 

Seconding what the previous posters said. If you want a good example of this behavior (program running from cron checks daemon and restarts if not running), look for example at start script for Apache

DVK
A: 

I would recommend to use an existing tool such as monit, it will monitor and auto restart processes. There is more information available here. It should be easily available in most distributions.

Zitrax