========================================================== ==========
This article is the original khler, and the original author information and the original link of this article must be kept completely and completely reprinted.
Author: HeYuanHui
E-mail: khler@163.com
QQ: 23381103
MSN: pragmac@hotmail.com
========================================================== ==========
How can I ensure that the service is always running? How can I ensure automatic restart even if the service fails? This problem is often encountered when writing a service program. In Linux, a powerful shell can handle such transactions flexibly.
The following shell uses a while-do loop and uses ps-ef | grep to check whether the loader process is running. If not, it starts, this ensures that the crashed process is restarted in time.
Note the following two points:
1. ps | grep must be added to a process; otherwise, grep may return incorrect results;
2. You must use-v to remove the grep command from the result. Otherwise, the result is not empty.Copy codeThe Code is as follows :#! /Bin/sh
#====================================
# YuanHui. HE
# Khler@163.com
#====================================
While:
Do
Echo "Current DIR is" $ PWD
StillRunning = $ (ps-ef | grep "$ PWD/loader" | grep-v "grep ")
If ["$ stillRunning"]; then
Echo "TWS service was already started by another way"
Echo "Kill it and then startup by this shell, other wise this shell will loop out this message annoyingly"
Kill-9 $ pidof $ PWD/loader
Else
Echo "TWS service was not started"
Echo "Starting service ..."
$ PWD/loader
Echo "TWS service was exited! "
Fi
Sleep 10
Done
If a process already exists when the shell is started, it means that the process has been started in other ways, instead of the shell, it will continue to remind you to find the process. The solution is either to use this shell to start the service, you can either kill a service that is started in another way once it is found, and the preceding statement is as follows:
Kill-9 $ pidof $ PWD/loader