linux下監視進程掛掉後自動重啓的shell腳本

本文介紹的這個shell腳本,經過一個while-do循環,用ps -ef|grep 檢查loader進程是否正在運行,若是沒有運行,則啓動,確保崩潰掛掉的進程,及時自動重啓。php

腳本內容以下:jquery

#!/bin/sh
while :
do
echo "Current DIR is " $PWD
stillRunning=$(ps -ef |grep "$PWD/loader" |grep -v "grep")
if [ "$stillRunning" ] ; then
echo "TWS service was already started by another way"
echo "Kill it and then startup by this shell, other wise this shell will loop out this message annoyingly"
kill -9 $pidof $PWD/loader
else
echo "TWS service was not started"
echo "Starting service ..."
$PWD/loader
echo "TWS service was exited!"
fi
sleep 10
done

注意:
一、ps |grep 一個進程時必須加上路徑,不然grep時會有不明錯誤;
二、必須用 -v 從結果中去除grep命令自身,不然結果非空。
shell

若是啓動此shell時發現進程已經存在,說明以別的方式啓動了進程而不是此shell,那麼它會持續提醒找到進程。
解決辦法:
只用此shell啓動服務,或一經發現以其餘方式啓動的服務即kill掉,即以上腳本中的這句來實現:
kill -9 $pidof $PWD/loaderapp

相關文章
相關標籤/搜索