比如我们想重启php-fpm。


1. #!/bin/bash
2.  
3. #变量初始化
4. process="php-fpm" #进程名
5. startCmd="/etc/init.d/php-fpm start" #启动命令
6. down=0
7.  
8. while true
9. do
10.     #取得http状态码
11.     code=$(curl -H "Host:www.centos.bz" -m 5 -L -s -w %{http_code} http://127.0.0.1 -o /dev/null)
12.     #当状态码返回000或者大于等于500时,计数故障到down变量
13.     if [ $code -eq 000 -o $code -ge 500 ];then
14.         ((down++))
15.     else
16. break
17.     fi
18.     #稍等5s
19.     sleep 5
20.     #判断是否连续检测三次都为故障.
21.     if [ $down -ge 3 ];then
22. if [ "$(find /tmp/${process}_restart -mmin -3)" == "" ];then
23.                 #取得进程名对应的所有pid
24. pids=$(ps aux | grep ${process} | grep -v "grep" | awk '{print $2}')
25.                 #依次对所有pid执行kill命令
26. for i in $pids;do
27. kill -9 $i
28. kill -9 $i
29. done
30.                 #kill完pid后,启动服务
31. $startCmd
32. echo "$(date) Return code $code,${process} had been restarted" >> /tmp/${process}_restart
33. else
34. echo "$(date) ${process} not yet recovery.As it had been restarted in 2 minutes.so this time ignore." >> /tmp/${process}_not_restart
35. fi
36.  
37. break
38.     fi
39. done