Shell腳本實現(xiàn)查殺子進程、僵尸進程
核心服務(wù)器上跑了一堆的腳本、程序,難免有時候會出現(xiàn)僵尸進程,死不死活不活的在那里占用資源,最初只是寫了個根據(jù)關(guān)鍵字查殺進程的linux shell腳本,后來發(fā)現(xiàn)很多時候進程死在那里的時候其實是內(nèi)部調(diào)用子進程的時候出現(xiàn)了問題,這時候光殺父進程根本沒解決根本問題。比如說rsync的時候通過ssh來連接,rsync本身沒問題,但可能ssh死掉了。因此重新寫了腳本,遞歸查找子進程。
#!/bin/sh
# 遞歸找到導致進程僵死的最底層子進程并殺除.
ParentProcessID=$1;
if [ "x${ParentProcessID}" = "x" ] ; then
echo "Please Supply the top Parent Process ID to be killed!"
echo "Usage:sh $0 PID [-v]"
echo "PID The Parent Process ID as root"
echo "-v is this argument supplied,no real kill operation will be performed,only process tree be show."
exit 1
fi
let IsRealKillDo=1;
if [ "x$2" = "x-v" ] ; then
let IsRealKillDo=0;
fi
echo "Begin Kill the Leaf Process of process ${ParentProcessID}" >&2
killpidList=""
function loopNextSubProcess(){
local nParentProcessID=$1
local tmpPidList=""
tmpPidList=`ps -A --format='%p%PisParent' --width 2048 -w --sort pid|grep "${nParentProcessID}isParent"|grep -v grep|grep -v "$$" | awk '{ printf $1 }'`
ps --format='%p%P%a' --width 2048 -w -p ${nParentProcessID}|grep -v grep|grep -v "$$" >&2
if [ "x${tmpPidList}" = "x" ] ; then
echo "****Got One Leaf = [${nParentProcessID}]****" >&2
killpidList="${killpidList}\n${nParentProcessID}"
return
fi
for theNextPid in ${tmpPidList} ; do
loopNextSubProcess ${theNextPid}
done
}
loopNextSubProcess ${ParentProcessID}
if [ ${IsRealKillDo} -eq 1 -a "x${killpidList}" != "x" ] ; then
for curpid in `echo -e ${killpidList}` ; do
if [ "x${curpid}" != "x" ] ; then
echo "kill -9 ${curpid}"
kill -9 ${curpid}
fi
done
else
echo -e ${killpidList}
fi
相關(guān)文章
shell腳本內(nèi)調(diào)用另外一個shell腳本的幾種方法講解
在Linux開發(fā)中經(jīng)常會編寫shell腳本來執(zhí)行一些任務(wù),下面這篇文章主要給大家介紹了關(guān)于shell腳本內(nèi)調(diào)用另外一個shell腳本的幾種方法,需要的朋友可以參考下2023-06-06
Shell中的for和while循環(huán)詳細總結(jié)
這篇文章主要介紹了Shell中的for和while循環(huán)詳細總結(jié),本文講解了for循環(huán)的數(shù)字段形式、詳細列出、對文件進行循環(huán),while循環(huán)的三種使用場合等內(nèi)容,需要的朋友可以參考下2015-05-05
Linux shell 獲得字符串所在行數(shù)及位置的方法
這篇文章主要介紹了Linux shell 獲得字符串所在行數(shù)及位置的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-08-08

