I jave written a small bash script to run every 10 minutes, check if a certain program is running and if not run it. However, I noticed that sometimes I have two instances of the same program running (using ps ax | grep "gateway"
). What am I doing wrong?
#! /bin/bash
case "$(ps ax | grep -c gateway.jar)" in
1) echo "Restarting Java Gateway (1): $(date)" >> /home/user/gateway.log
java -jar /home/user/project/unx/java/gateway.jar &
;;
0) echo "Restarting Java Gateway (0): $(date)" >> /home/iwidgetuser/gateway.log
java -jar /home/user/project/unx/java/gateway.jar &
;;
*) echo "Gateway is running! Good!: $(date)" >> /home/user/gateway.log
;;
esac
Best Answer
Your check is program is running is incorrect.
You obtain list of running processes and search in them string with your program name (
gateway.jar
). If string occured in processes list 0 or 1 times you startgateway.jar
.If
gateway.jar
is still running it will be in process list. Also, ifgrep
invocation was caught in process list, it's command will containgateway.jar
and it will be counted bygrep
.So there are three four cases:
gateway.jar
is running andgrep
is in process list ->grep
returns 2gateway.jar
is running andgrep
is not in process list ->grep
returns 1gateway.jar
is not running andgrep
is in process list ->grep
returns 1gateway.jar
is not running andgrep
is not in process list ->grep
returns 0If case 2 happens your code starts
gateway.jar
second time.Case 2 happens rarely, e.g. on my machine it happened 4 times out of 1000 invocations: