奇诺分享 | ccino.org

  • 首页
  • VPS
    • VPS申请
    • VPS配置
    • 科学上网
  • 网站建设
    • WordPress
  • 程序猿
    • 开发工具
    • 微服务
    • 容器
    • 分布式
    • 数据库
    • 人工智能
  • 杂项
  • 关于
  • Privacy Policy
生活不只是眼前的苟且,还有诗和远方!
  1. 首页
  2. VPS
  3. VPS配置
  4. 正文

linux下用脚本实现:监控一个进程,不存在则将其启动

2018年3月28日 1508点热度 0人点赞 0条评论

[title]方法1:[/title]

#!/bin/bash

while [ 1 ]
do
procID=`pgrep test`
if [ "" == "$procID" ];
then
/root/test -d
fi
usleep 1000
done &

注:1、pgrep 根据给出的进程名判断是否有这个名字的进程。如果有这个名字的进程正常退出,退出值0.如果没有这个名字的进程异常退出,退出值1。

2、ps -p 根据给定的pid参数判断是否有这个进程,如果有这个进程正常退出,退出值0.如果没有这个进程异常退出,退出值1。
例如: apple@ubuntu:~$ ps -p 2442

3、最后加 & 符号,表示让脚本在后台执行,即将shell关闭后 程序仍在运行。

下边是监控多个进程,只需添加一个循环:

#!/bin/bash

while [ 1 ]
do

for procname in proc1 proc2  #需要检测的进程名字

do
procID=`pgrep $procname`
if [ "" == "$procID" ];
then
/root/$procname-d
fi

done
usleep 1000
done &

另附参考例子:

#!/bin/sh

#其实sh是链接到busybox的

while [1 -eq 1]  #死循环
do 
   for procname in proc1 proc2  #需要检测的进程名字
   do
      pgrep $procname
      if [0 -ne $? ]  #如果进程不存在就重启它
      then
         ./$prconame
      fi
   done
   sleep 10
done

[title]方法2:[/title]

服务器上运行了一些小工具属于非服务类的,程序进程本身不是很稳定总是异常关闭写个脚本监视它,判断进程是否存在并启动该进程。

1.Linux判断进程是否存在并启动该进程

#!/bin/bash
#判断进程是否存在,如果不存在就启动它
PIDS=`ps -ef |grep myprocess |grep -v grep | awk '{print $2}'`
if [ "$PIDS" != "" ]; then
echo "myprocess is runing!"
else
cd /root/
./myprocess
#运行进程
fi

2.linux判断进程是否存在并重启该进程

#!/bin/bash
#判断进程是否存在,如果不存在就启动它如果存在就重启它
PIDS=`ps -ef |grep myprocess |grep -v grep | awk '{print $2}'`
if [ "$PIDS" != "" ]; then
kill -9 $PIDS
#先关闭进程,在运行此进程
cd /root/myprocess
sudo ./myprocess
#重新运行进程
else
cd /root/myprocess
sudo ./myprocess
#运行进程
fi

最后编辑crontab -e 按需要设置运行时间。

 

本文出自:https://blog.csdn.net/dc_show/article/details/41806265

http://lib.csdn.net/article/linux/33370

 

标签: crontab 进程
最后更新:2018年3月28日

奇诺分享 | ccino.org

这个人很懒,什么都没留下

点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理。

COPYRIGHT © 2022 奇诺分享 | ccino.org. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang