简体   繁体   English

如果服务死了,我该如何编写bash脚本来重新启动服务?

[英]How do I write a bash script to restart a service if it dies?

I have a program that runs as a daemon, using the C command fork(). 我有一个使用C命令fork()作为守护程序运行的程序。 It creates a new instance that runs in the background. 它创建一个在后台运行的新实例。 The main instance exists after that. 之后,主要实例存在。

What would be the best option to check if the service is running? 检查服务是否正在运行的最佳选择是什么? I'm considering: 我正在考虑:

  • Create a file with the process id of the program and check if it's running with a script. 使用程序的进程ID创建一个文件,并检查它是否正在使用脚本运行。
  • Use ps | grep 使用ps | grep ps | grep to find the program in the running proccess list. ps | grep在运行的进程列表中找到该程序。

Thanks. 谢谢。

我认为最好使用supervisor或其他过程控制系统来管理您的过程。

Create a cron job that runs every few minutes (or whatever you're comfortable with) and does something like this: 创建一个每隔几分钟(或您喜欢的任何时间)运行的cron作业,并执行以下操作:

/path/to/is_script_stopped.sh && /path/to/script.sh

Write is_script_stopped.sh using any of the methods that you suggest. 使用您建议的任何方法编写is_script_stopped.sh If your script is stopped cron will evaluate your script, if not, it won't. 如果您的脚本停止了,则cron会评估您的脚本,否则,不会。

To the question, you gave in the headline: 对于这个问题,您在标题中给出了:

This simple endless loop will restart yourProgram as soon as it fails: 这个简单的无穷循环将在失败后立即重新启动yourProgram:

#!/bin/bash
for ((;;))
do
   yourProgram
done

If your program depends on a resource, which might fail, it would be wise to insert a short pause, to avoid, that it will catch all system resources when failing million times per second: 如果您的程序依赖于可能会失败的资源,则明智的做法是插入一个短暂的暂停,以避免每秒每秒失败百万次时捕获所有系统资源:

#!/bin/bash
for ((;;))
do
   yourProgram
   sleep 1
done

To the question from the body of your post: 对您的帖子正文提出的问题:

What would be the best option to check if the service is running? 检查服务是否正在运行的最佳选择是什么?

If your ps has a -C option (like the Linux ps) you would prefer that over a ps ax | grep 如果您的ps具有-C选项(例如Linux ps),则您更喜欢使用ps ax | grep ps ax | grep combination. ps ax | grep组合。

 ps -C yourProgram

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM