暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Linux如何限制cpu使用,用 cpulimit 防止 CPU 过载而翻车

IT运维大爆炸 2021-08-25
4154

1、软件包

文章所需软件包下载方式

2、简介

cpulimit 就是一款可以对 CPU 使用率进行控制的软件。如何使用 cpulimit 防止老司机在 ECS 上翻车。很多朋友如果只是购买的单核心实例,如果跑的 MYSQL 过载了或者遭遇一些逻辑缺陷的软件造成 CPU 过载和服务器假死,导致网站打不开或者 502 错误啥的。所以我们可以借助一些软件来限制 CPU 的使用率和 IO。还有千万不要用跑分软件跑分,不然准翻车。

3、安装

[root@instance-iq88yiwv ~]# yum install cpulimit

4、使用说明

[root@instance-iq88yiwv ~]# 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)

5、用法

#限制firefox使用30% cpu 利用率 
[root@instance-iq88yiwv ~]# cpulimit -e firefox -l 30

#限制进程号1313的程序使用30% cpu 利用率
[root@instance-iq88yiwv ~]# cpulimit -p 1313 -l 30

#限制绝对路径下该软件的 cpu 利用率
[root@instance-iq88yiwv ~]# cpulimit -e usr/local/nginx/sbin/nginx -l 50

6、注意事项

  • 一定要放到后台执行,否则执行之后不能关闭页面。

  • -l后面限制的cpu使用量,要根据实际的核心数量而成倍减少。40%的限制生效在1核服务器中,如果是双核服务器,则应该限制到20%,四核服务器限制到10%以此类推。

  • root用户可以限制所有的进程,普通用户只能限制自己有权限管理的进程。

7、限制所有进程的 CPU 使用率

默认情况下 cpulimit 只能对已经存在的进程进行限制,但是设置此脚本为随机自启动即可(设置方法参看上面的脚本链接中),它会对所有进程(包括新建进程)进行监控并限制(3秒检测一次,CPU限制为75%)

# 这就可以防止因为 CPU 使用率过高而被 suspend 了!
#!/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

8、设置为开机启动

修改 /etc/rc.local 在对应位置加入 /root/cpulimit.sh 再重启系统,就会全程限制各个进程的 CPU 使用了!

[root@jky-de ~]# vim /etc/rc.local
sh /root/cpulimit.sh

欢迎大家扫码关注:

本公众号只写原创,不接广告、不接广告、不接广告。下期小伙伴想学习什么技术,可以私信发我吆。

文章转载自IT运维大爆炸,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论