代码改变世界

脚本监控Linux、mac或windows某个后台进程,当进程死掉后重新启动服务,以stf为例

2021-08-05 20:55  Tanwheey  阅读(365)  评论(0编辑  收藏  举报

1、linux:

#!/bin/bash

while true
flag=`ps -ef |grep "stf" |grep -v "grep" |wc -l`
do
        if [[ $flag -eq 0 ]]
        then
               echo ">>>>no stf,run it"
        sh /root/yunji/startstf.sh
         echo $(date "+%Y%m%d-%H%M%S") - "stf restart" >> running.log
        else
        echo ">>>>main is running"
                echo "stf is running..." >> /dev/null
        fi
        sleep 10s
done

 

2、mac:

vi restartstf.sh

#!/bin/bash

while true   # 无限循环
flag=`ps -ef |grep "stf" |grep -v "grep" |wc -l`  #“ps -aux | grep”查找进程,“grep -v "grep"”排除 grep 本身这个进程,“wc -l”统计进程数
do
        if [[ $flag -eq 0 ]]   # 判断进程数如果等于0,则启动stf
        then
           	echo ">>>>no stf,run it"
	        `cd /root/clouddevice/stf`   # 进入stf文件夹
		`nohup stf local --public-ip xx.xx.xx --bind-dev-pull tcp://0.0.0.0:7114 --bind-dev-pub tcp://0.0.0.0:7116 -R > stf.log &`  #启动stf
                echo 'date' - "stf restart" >> running.log   # 将重启时间写入自定义的日志文件
        else
		echo ">>>>main is running"
                echo "stf is running..." >> /dev/null
        fi
        sleep 3s  # 延迟3秒后进入下次循环
done

 运行脚本:bash restartstf.sh &  #&:将这个任务放到后台去执行

直接执行脚本 sh restartstf.sh:

 

 

 2、windows:

restartstf.bat:

@echo off
set DestBat=D:\Desktop\stf.bat
set AppName=stf

title stf-watcher
cls
:startstf
	qprocess|findstr /i %AppName% >nul
	if %errorlevel%==0 (
        echo ^>%date:~0,10% %time:~0,8% stf is running...
    ) else (
	    echo ^>%date:~0,10% %time:~0,8% not found stf!
	    echo ^>%date:~0,10% %time:~0,8% restart stf process!
	    start %DestBat% 2>nul && echo ^>%date:~0,10% %time:~0,8% start stf success!
   )
for /l %%i in (1,1,10) do ping -n 1 -w 2000 'IP地址'>nul
   goto startstf
echo on

restartstf.bat:

@echo off
start stf

 启动:

进入bat文件路径下:

%xxx.bat