NeDark
NeDark

Reputation: 1294

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 the best option to check if the service is running? I'm considering:

Thanks.

Upvotes: 2

Views: 2248

Answers (3)

user unknown
user unknown

Reputation: 36269

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

Upvotes: 0

Leon
Leon

Reputation: 2896

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

Upvotes: 1

Chris
Chris

Reputation: 3050

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.

Upvotes: 0

Related Questions