如何在bash中编写看门狗守护程序? [英] How do I write a watchdog daemon in bash?

查看:130
本文介绍了如何在bash中编写看门狗守护程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一种在shell脚本中编写守护程序的方法,该守护程序将在循环中运行另一个应用程序,如果死了,则重新启动它。

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


  • 在SSH会话中使用 ./ myscript.sh 运行时,它将启动该守护程序的新实例,除非该守护程序已在运行。

  • 当SSH会话结束时,守护程序将继续存在。

  • 应该有一个参数( ./ myscript -stop )杀死所有现有的守护程序。

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

有关编辑的注意事项 -最初的问题指出,不得使用 nohup 和类似的工具。这种人为的要求是 XY问题,并且接受的答案实际上使用了OP声称无法使用的所有工具。)

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

推荐答案

基于注释中的说明,您真正想要的是一个守护进程,该进程可使孩子保持运行状态,并在退出时重新启动它。您需要一种在ssh会话中键入 ./myscript.sh并启动守护程序的方法。

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

运行脚本:它将使用nohup为您启动守护进程。守护进程是一个循环,监视子进程退出,并在子进程退出时重新启动。

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.

要控制守护进程,有一个-脚本可以接受的stop 参数将杀死守护程序。在系统的初始化脚本中查看示例,以获取更完整的示例以及更好的错误检查功能。

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.

这篇关于如何在bash中编写看门狗守护程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆