Use cron, grep, ps to monitor and restart a program (x11vnc)

As a band-aid to check if a program stopped running, and then restart it if it did stop, here is what I came up with.  x11vnc is the program that gave me trouble, seems like every once in a while, usually while I’m logging in as a user and the X11 screen changes, the VNC server loses its mind and quits.  Being lazy, I don’t want to remember the command to type in to restart it correctly, so this does it for me:

Step 1:

create a shell script (/root/check-x11vnc-running)(and chmod +x to make executable):

 # Check to see if x11vnc is running
 if ps cax | grep x11vnc | grep -v check >; /dev/null
      echo "x11vnc running when checked at $(date)" >> /var/log/x11vnc-checker.log
      x11vnc -usepw -nap -wait 50 -noxdamage -display :0 -forever -o /var/log/x11vnc.log -bg
      echo "Restarted x11vnc at $(date)" >> /var/log/x11vnc-checker.log
  • ps cax lists all the processes running, grep finds all the lines that mention x11vnc, and the second grep command removes the instance of this script running.
  • if the statement was > 0, we think the program is running, make an entry to a log file (have to create the file to start with —  use ‘touch /var/log/xxxxx’)
  • if the statement was false (a zero), issue the command to restart the vnc server, and make a log entry

Step 2:

add a entry to crontab to run the script above once every minute

 > crontab -e
*/1 * * * * /root/check-x11vnc-running  

I had fits getting this to work, and finally figured it out.  The first entry represents the minute, so I figured ‘run every minute’ would be a ‘*’.  But, it won’t run with all *’s, the ‘*/1’ makes it run once per minute.  ‘*/2’ is every two minutes.  ‘2’ would be at H:02 of every hour.

This entry was posted in Uncategorized. Bookmark the permalink.