1. 程式人生 > >Linux VPS通過安裝CPULimit來限制CPU使用率

Linux VPS通過安裝CPULimit來限制CPU使用率

tab $2 color ogr this ech program ces 可執行

說明:我們手上經常有很多廉價的VPS,有時候使用某些軟件應用的時候,會出現CPU跑滿的情況,而長時間跑滿會被VPS商家停掉,所以這裏我們需要想辦法來限制進程CPU使用率,這裏就說個教程。

簡介

cpulimit命令的工作原理是為進程預設一個cpu占用率上限,並實時監控進程是否超出此上限,而做出動態調整。從而可以控制進程的cpu使用率的上限值。

安裝

使用root運行命令:

#debian/ubuntu系統
apt install -y cpulimit

#RHEL/Centos/Fedora系統
yum install epel-release cpulimit

使用

cpulimit -h
Usage: cpulimit [OPTIONS...] TARGET
   OPTIONS
      
-l, --limit=N percentage of cpu allowed from 0 to 100 (required)//cpu限制的百分比 -v, --verbose show control statistics//顯示版本號 -z, --lazy exit if there is no target process, or if it dies//如果限制的進程不存在了,則退出。 -i, --include-children limit also the children processes//包括子進程。
-h, --help display this help and exit //幫助,顯示參數 TARGET must be exactly one of these: -p, --pid=N pid of the process (implies -z) //進程的pid -e, --exe=FILE name of the executable program file or path name //可執行程序 COMMAND [ARGS] run this command and limit it (implies -z)

用法

1、常規用法

#限制firefox使用30% cpu利用率
cpulimit -e firefox -l 30

#限制進程號1313的程序使用30%cpu利用率
cpulimit -p 1313 -l 30

#限制絕對路徑下該軟件的cpu利用率
cpulimit -e /usr/local/nginx/sbin/nginx -l 50

2、限制所有進程的CPU使用率
默認情況下cpulimit只能對已經存在的進程進行限制,但是設置此腳本為隨機自啟動即可,它會對所有進程(包括新建進程)進行監控並限制(3秒檢測一次,CPU限制為75%

這就可以防止因為CPU使用率過高而被ban了!

#!/bin/bash 

while true ; do

  id=`ps -ef | grep cpulimit | grep -v "grep" | awk {print $10} | tail -1`

  nid=`ps aux | awk { if ( $3 > 75 ) print $2 } | head -1`

  if [ "${nid}" != "" ] && [ "${nid}" != "${id}" ] ; then

    cpulimit -p ${nid} -l 75 &

    echo "[`date`] CpuLimiter run for ${nid} `ps -ef | grep ${nid} | awk ‘{print $8}‘ | head -1`" >> /root/cpulimit-log.log

  fi

  sleep 3

done

保存到 /root/cpulimit.sh,會自動生成日誌文件 /root/cpulimit-log.log

然後修改 /etc/rc.local 在對應位置加入 /root/cpulimit.sh 再重啟系統,就會全程限制各個進程的CPU使用了!

註意事項

l、後面限制的cpu使用量,要根據實際的核心數量而成倍減少。40%的限制生效在1核服務器中,如果是雙核服務器,則應該限制到20%,四核服務器限制到10%以此類推。
2、root用戶可以限制所有的進程,普通用戶只能限制自己有權限管理的進程。

Linux VPS通過安裝CPULimit來限制CPU使用率