3

I'm using Monit to monitor a system. I have a python file I wish to also monitor, I understand that I need to create a wrapper script as python does not generate pid files. I followed the instructions on this site, however I have been unable to get the script to start. I've never created a wrapper script before, so I think I have an error in my script. The log from monit says "Failed to start"

Monit rule

check process scraper with pidfile /var/run/scraper.pid
   start = "/bin/scraper start"
   stop = "/bin/scraper stop"

wrapper script

#!/bin/bash

PIDFILE=/var/run/scraper.pid

case $1 in
   start)
      echo $$ > ${PIDFILE};
      source /home
      exec python /home/scraper.py 2>/dev/null
   ;;
   stop)
      kill `cat ${PIDFILE}` ;;
   *)
      echo "usage: scraper {start|stop}" ;;
esac
exit 0
Jim
  • 1,337
  • 5
  • 20
  • 29

2 Answers2

7

Using exec will replace the shell by the exec'd program, this is not what you want to get here, you want your wrapper script to launch the program and detach it before returning, writing its PID to a file so it can be stopped later.

Here's a fixed version:

#!/bin/bash

PIDFILE=/var/run/scraper.pid

case $1 in
   start)
       source /home
       # Launch your program as a detached process
       python /home/scraper.py 2>/dev/null &
       # Get its PID and store it
       echo $! > ${PIDFILE} 
   ;;
   stop)
      kill `cat ${PIDFILE}`
      # Now that it's killed, don't forget to remove the PID file
      rm ${PIDFILE}
   ;;
   *)
      echo "usage: scraper {start|stop}" ;;
esac
exit 0
  • 1
    I don't really follow why source is used, since the link in the question now goes to a 404. Could this be commented? Also, what are the two files called and where are they located? Thanks :) – Aaron Jul 24 '15 at 15:08
  • I think this will stop the script – Braconnot_P Apr 01 '22 at 16:51
2

You could also bypass the whole wrapper thing entirely by adding a small function that writes the pidfile inside your script. Something such as:

import os

def writePidFile():
    pid = str(os.getpid())
    currentFile = open(‘/var/run/myPIDFile.pid’, ‘w’)
    currentFile.write(pid)
    currentFile.close()

I found myself using this method instead since it is a much more straight forward approach and it is self contained in the script.

Markov Chained
  • 55
  • 1
  • 10
  • How do you handle start/stop actions? – EnemyBagJones Dec 11 '17 at 00:03
  • Follow the instructions from the tutorial website. The PID file is nothing more than the Process ID so that the program/script can be started/stopped. You still have to define those as per the instructions here: https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-monit – Markov Chained Dec 12 '17 at 22:33