脚本1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45!/bin/bash
###############################################################################
# ##
# linux进程守护脚本 ##
# ##
###############################################################################
if [ -f ~/.bash_profile ]; then
source ~/.bash_profile
fi
log() {
msg=$1
date_str=`date +"%Y-%m-%d %H:%M:%S"`
echo "[$date_str] $msg"
}
curdir=`dirname $0`
config_file=daemon.config
app_log_dir=logs
config_file_full=$curdir/$config_file
app_log_dir_full=$curdir/$app_log_dir
log "begin to monitor"
cat $config_file_full | while read line
do
name=`echo "$line" | awk -F '###' '{print $1}'`
process=`echo "$line" | awk -F '###' '{print $2}'`
if [ -z "$name" ] || [ -z "$process" ] ; then
echo "$name config error"
continue
fi
count=`ps -ef | grep "$process" | grep -v grep | grep $USER | wc -l`
log "$name: $count"
if [ $count -gt 0 ]; then
log "$name is alived"
else
process &
log "$name is dead, restart"
fi
done
log "end to monitor"
添加脚本配置文件daemon.config
配置文件格式为 程序名称###启动命令. 例如
1 | ##/usr/local/nginx/sbin/nginx |
添加crontab每2分钟运行一次脚本1
2crontab -e
*/2 * * * * sh /scriptDir/daemon.sh >> /scriptDir/logs/daemon.log 2>&1