- 利用cpulimit限制cpu的使用情况需要手动,很是麻烦。写一个shell脚本以root权限运行可以自动控制选定用户的程序。如果cpu占用超过了阈值400,脚本自动压制到200.
nohup bash Auto_watch_and_limit_cpu.sh &
#!/bin/bash
arr=(
"user1"
"user2"
"user3"
)
# set limit cpu usage
cpul=400
cpus=200
# show basic info
echo " "
echo " We will limit the users below when the cpu usage of their pid is over the threshold "$cpul"."
for value in ${arr[@]}
do
echo " "$value
done
# check and cpulimit
echo "---------------------------------------------------------"
while :
do
top -bn1 | awk '{if(NR>=8 && $9>'${cpul}')print ($1,$2,$9)}' | while read pid user cpu
do
echo ' pid='$pid,'user='$user,'cpu='$cpu
if [[ "${arr[*]}" =~ ${user} ]] ; then
echo " cpulimit -p "${pid}" -l "$cpus
cpulimit -p ${pid} -l $cpus
fi
done
echo "---------------------------------------------------------"
sleep 1
done
-
程序运行截图