Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a watchdog daemon in bash?

I want a way to write a daemon in a shell script, which runs another application in a loop, restarting it if it dies.

  • When run using ./myscript.sh from an SSH session, it shall launch a new instance of the daemon, except if the daemon is already running.
  • When the SSH session ends, the daemon shall persist.
  • There shall be a parameter (./myscript -stop) that kills any existing daemon.

(Notes on edit - The original question specified that nohup and similar tools may not be used. This artificial requirement was an "XY question", and the accepted answer in fact uses all the tools the OP claimed were not possible to use.)

like image 372
Alexey Kamenskiy Avatar asked Feb 20 '23 11:02

Alexey Kamenskiy


1 Answers

Based on clarifications in comments, what you actually want is a daemon process that keeps a child running, relaunching it whenever it exits. You want a way to type "./myscript.sh" in an ssh session and have the daemon started.

#!/usr/bin/env bash
PIDFILE=~/.mydaemon.pid
if [ x"$1" = x-daemon ]; then
  if test -f "$PIDFILE"; then exit; fi
  echo $$ > "$PIDFILE"
  trap "rm '$PIDFILE'" EXIT SIGTERM
  while true; do
    #launch your app here
    /usr/bin/server-or-whatever &
    wait # needed for trap to work
  done
elif [ x"$1" = x-stop ]; then
  kill `cat "$PIDFILE"`
else
  nohup "$0" -daemon
fi

Run the script: it will launch the daemon process for you with nohup. The daemon process is a loop that watches for the child to exit, and relaunches it when it does.

To control the daemon, there's a -stop argument the script can take that will kill the daemon. Look at examples in your system's init scripts for more complete examples with better error checking.

like image 153
Nicholas Wilson Avatar answered Feb 27 '23 22:02

Nicholas Wilson