开发者

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(). It creates a new instance that runs in the background. The main instance exists after that.

What would be 开发者_StackOverflowthe 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.
  • Use ps | grep to find the program in the running proccess list.

Thanks.


I think it will be better to manage your process with supervisord, or other process control system.


Create a cron job that runs every few minutes (or whatever you're comfortable with) and does something like this:

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

Write is_script_stopped.sh using any of the methods that you suggest. If your script is stopped cron will evaluate your script, if not, it won't.


To the question, you gave in the headline:

This simple endless loop will restart yourProgram as soon as it fails:

#!/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 combination.

 ps -C yourProgram
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜