pythonubuntuservicestart-stop-daemonpyinotify

custom linux daemon won't stop using "service stop"


I've written a custom python daemon that runs as a service via an init.d script on ubuntu 14.04. Starting the service works fine, but when I try to do "service monitor stop", the daemon is not terminated. I'm using pyinotify to daemonize a file watcher for changes.

Within the init.d script:

PATH=/sbin:/usr/sbin:/bin:/usr/bin
DESC="Monitor files"
NAME=monitor
DAEMON=/usr/bin/python
DAEMON_ARGS="/home/user/python/monitor.py"
PIDFILE=/home/user/logs/monitor.pid
LOGFILE=/home/user/logs/monitor.log
SCRIPTNAME=/etc/init.d/$NAME

...

do_stop()
{
    # Return
    #   0 if daemon has been stopped
    #   1 if daemon was already stopped
    #   2 if daemon could not be stopped
    #   other if a failure occurred
    start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name $NAME
    RETVAL="$?"
    # Many daemons don't delete their pidfiles when they exit.
    rm -f $PIDFILE
    return "$RETVAL"
    echo "done"
}

...

case "$1" in
  start)
    [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
    do_start
    case "$?" in
            0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
            2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
    esac
    ;;
  stop)
    [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
    do_stop
    case "$?" in
            0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
            2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
    esac
    ;;

...

To ensure the daemon handles SIGERM properly, I can run it by hand:

bash$ /usr/bin/python /home/user/python/monitor.py
bash$ kill -Term PID

The daemon successfully handles the SIGTERM and exits properly.

I can't seem to figure out why it doesn't handle it when I do "service monitor stop" though.


Solution

  • Check that the process $NAME is correct, as delivered to the start-stop-daemon --stop command. I just encountered this issue because a process I was running ended up getting a different name whenever it forked its daemon. Try running this to see the process command name:

    ps -o comm= $(cat /home/user/logs/monitor.pid)
    

    I bet yours outputs this (instead of monitor):

    python
    

    Then change your stop command to look like this, where you substitute python in place of $NAME:

    start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name python