How do I write a watchdog daemon in bash?

天大地大妈咪最大 提交于 2019-12-08 02:27:06

问题


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.)


回答1:


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.




回答2:


The pid of the most recently "backgrounded" process is stored in $!

$ cat &
[1] 7057
$ echo $!
7057

I am unaware of a fork command in bash. Are you sure bash is the right tool for this job?



来源:https://stackoverflow.com/questions/12025790/how-do-i-write-a-watchdog-daemon-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!