Shell脚本实现查杀子进程、僵尸进程
核心服务器上跑了一堆的脚本、程序,难免有时候会出现僵尸进程,死不死活不活的在那里占用资源,最初只是写了个根据关键字查杀进程的linux shell脚本,后来发现很多时候进程死在那里的时候其实是内部调用子进程的时候出现了问题,这时候光杀父进程根本没解决根本问题。比如说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
上一篇: 官方致歉:黑鲨3 Pro开售时间延期至3月27日 全力提拉产能
下一篇: 主板经常不能开机的故障原因