shell脚本,监控后台进程
上一篇 /
下一篇 2013-04-15 17:34:22
/ 个人分类:Linux Shell
从今天开始结合
工作中的实际应用,不定期和大家分享下
shell脚本或者python脚本
需求:要求监控某个进程,当进程结束掉的时候,自动重启该进程。
实现:
#! /bin/bash
#monitor apa_ris, restart it when the progress is down.
while true
do
PROSS=`ps -el|grep apa_ris|awk '{ print $14 }'`
if [[ $PROSS != "apa_ris" ]]; then
echo "The programm has dropped";
echo "Now, restart";
/usr/local/apa1/bin/startapa.sh
sleep 20
fi
continue
done
讲解:
1. 使用一个while true循环,实现监控功能,无限循环,查看该进程是否存在,shell中的while循环结构是
while 条件
do
“something you want to do"
done
2. ps -el|grep apa_ris 过滤apa_ris 进程,其实ps -ef是我经常使用的,下面是区别
bash-3.2# ps -ef|grep apa_ris
root 18094 28101 0 17:58:33 pts/3 0:00 grep apa_ris
root 18092 1 0 17:58:27 ? 0:00 /usr/local/apa1/sbin/apa_ris
bash-3.2# ps -el|grep apa_ris
0 S 0 18092 1 0 40 20 ? 5441 ? ? 0:00 apa_ris
可以看到,-el不显示grep命令本身
3. 使用awk,将需要的字段取出
4. sleep 20,这里让程序休眠20s,单位是秒,为什么要休眠,因为在脚本实际运行的时候,出现了这样的情况,当无apa_ris进程运行的时候,脚本会启动,但是进程启动需要时间,而第二次循环判断的时候,却出现进程还未启动的情况。
5. continue,结合while,实现循环查询。
写脚本过程中遇到的问题:
1. if [[ $PROSS != "apa_ris" ]],两个中括号
最一开始写成了,一个中括号 if [ $PROSS != "apa_ris" ],发现提示
请参考http://blog.csdn.net/goodlixueyong/article/details/6564591,谢作者
收藏
举报
TAG: