由於集群用戶經常會不懂如何提交作業,將作業直接運行到登錄節點上,這樣導致登錄節點的cpu及內存占用很大,導致其他用戶甚至無法登錄。所以就想到了一種解決方法,寫一個shell腳本,常駐登錄節點,監控cpu占用率,如果某一進程占用cpu超過90%,且運行時間超過十五秒,就直接kill掉。shell腳本代碼如下:
#!/bin/sh
while true
do
sleep3
#循環查看占用cpu超過90%的進程ID
/bin/ps axf -o "pid %cpu" | awk '{if($2>=90) print $1}' | while read procid
do
#進程詳細信息
pro=$(ps -A|grep "\\<$procid\\>" |sort -k3,3|head -n1)
#獲取進程運行的時間,如果大於15秒,設time為1,如若不是則設time為0
time="$(echo $pro|awk '{
split($3,tab,/:/); if (tab[3]>=15) {print 1}else{print 0}
}')"
#如果time1,則kill掉該進程
if [ $time = '1' ];then
kill -9 $procid
fi
done
done
最后運行 nohup ./你寫的shell腳本 > cpucheck.log 2>&1 & 以保證它在后台長期運行