Question

I want to restart a process (python script) automatically if it ends/crashed. Below my bash init.d script so far. I was thinking to replace the do_start() call in the start section with:

until do_start; do
   echo "Restarting.." >> error.txt
   sleep 1
done

Unfortunately this seems not to be working. My script is not restarting. Has anyone a tip?

#!/bin/bash

### BEGIN INIT INFO
# Provides:          RPiQuadroServer
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Put a short description of the service here
# Description:       Put a long description of the service here
### END INIT INFO

WORK_DIR="/var/lib/RPiQuadroServer"
DAEMON="/usr/bin/python"
ARGS="/usr/local/bin/RPiQuadroServer.py"
PIDFILE="/var/run/RPiQuadroServer.pid"
USER="root"

. /lib/lsb/init-functions

do_start() {
  log_daemon_msg "Starting system $DAEMON $ARGS daemon"
  mkdir -p "$WORK_DIR"
  /sbin/start-stop-daemon --start --pidfile $PIDFILE \
    --user $USER --group $USER \
    -b --make-pidfile \
    --chuid $USER \
    --exec $DAEMON $ARGS
  log_end_msg $?
}

do_stop() {
  log_daemon_msg "Stopping system $DAEMON $ARGS daemon"
  /sbin/start-stop-daemon --stop --pidfile $PIDFILE --verbose
  log_end_msg $?
}

case "$1" in
  start)
    do_start
    ;;
  stop)
    log_daemon_msg "Stopping system $DAEMON $ARGS daemon"
    do_stop
    ;;
  restart|reload|force-reload)
    do_stop
    do_start
    ;;
  status)
    status_of_proc "$DAEMON $ARGS" "$DAEMON $ARGS" && exit 0 || exit $?
    ;;
  *)
    echo "Usage: /etc/init.d/$USER {start|stop|restart|status}"
    exit 1
    ;;
esac
Was it helpful?

Solution

You need to have some kind of a supervision. For example monit. It will do what you described: start/restart process:

For example:

check process RPiQuadroServe pidfile /var/run/RPiQuadroServer.pid                      
 start program = "/etc/init.d/RPiQuadroServe start"                               
 stop program = "/etc/init.d/RPiQuadroServec stop"                                 

OTHER TIPS

In the until loop, the loop executes until the do_start command executes successfully, which means it continues as long as do_start exits with any exit code other than 0. But in your code, you didn't set any exit status, so it would be 0. You might want to set the exit code by for example return $? after executing Python code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top