Tuesday, October 17, 2017

Check Running Process

What we'd like to do here is to check for the presence of a running process. If present, do x (echo Running). If not, do y (restart said process).

First step is typically done by running ps and doing a grep on the output for the process name (ps -ef|grep process). This merely checks for presence and not the state of the process. In the case of no match, grep will still match the original grep command, thus reporting a hit. To get around this, do an inverse-match for grep (ps -ef|grep -v grep|grep process). Another option is to use pgrep.

So you'd have something like this:
#!/bin/sh

if ps ax | grep -v grep | grep process > /dev/null
then
    echo "Running"
else
    echo "Not running. Starting."
    /opt/process/bin/process restart
fi

If you plan to run the script as a cron job, best to silence all output (/opt/process/bin/process restart &> /dev/null).
Or better yet, run the check commands as the cron job itself (every 15 minutes):
*/15 * * * * pgrep process > /dev/null || /opt/process/bin/process restart &> /dev/null

No comments:

Post a Comment