如何在 bash 中编写看门狗守护进程?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12025790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:04:13  来源:igfitidea点击:

How do I write a watchdog daemon in bash?

bashshelldaemonnohup

提问by Alexey Kamenskiy

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

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

  • When run using ./myscript.shfrom 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.
  • ./myscript.sh从 SSH 会话运行 using 时,它将启动守护进程的新实例,除非守护进程已经在运行。
  • 当 SSH 会话结束时,守护进程将持续存在。
  • 应该有一个参数 ( ./myscript -stop) 可以杀死任何现有的守护进程。


(Notes on edit- The original question specified that nohupand 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.)

编辑注意事项- 原始问题指定nohup不得使用类似工具。这个人为的要求是一个“XY 问题”,实际上接受的答案使用了 OP 声称不可能使用的所有工具。)

回答by Nicholas Wilson

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.

根据评论中的说明,您真正想要的是一个守护进程,它可以让子进程保持运行,并在它退出时重新启动它。您想要一种在 ssh 会话中键入“./myscript.sh”并启动守护程序的方法。

#!/usr/bin/env bash
PIDFILE=~/.mydaemon.pid
if [ x"" = 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"" = x-stop ]; then
  kill `cat "$PIDFILE"`
else
  nohup "
$ cat &
[1] 7057
$ echo $!
7057
" -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.

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

To control the daemon, there's a -stopargument 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.

为了控制守护进程,-stop脚本可以采用一个参数来杀死守护进程。查看系统初始化脚本中的示例以获取更完整的示例,并进行更好的错误检查。

回答by glenn Hymanman

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

最近“背景化”进程的 pid 存储在 $!

##代码##

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

我不知道forkbash中的命令。您确定 bash 是适合这项工作的工具吗?