CentOS 7使用cgroup限制cpu使用率教程(替代cpulimit)

什么是cgroups?

cgroups是linux内核自带的控制组群,使用cgroup可以限制、控制与分离一个进程组的资源.
https://zh.wikipedia.org/wiki/Cgroups

安装cgroup以及cgroup工具


yum install -y libcgroup libcgroup-tools

挂载cgroup子系统

cgroup在系统目录已经默认挂载了,没有必要自定义挂载
lssubsys -am #查看默认挂载的子系统

cgconfig配置CPU使用率限制(其他限制参考末尾文章)

/etc/cgconfig.conf
echo -ne "
group limitcpu{
        cpu {
                cpu.shares = 400;
        }
}
group limitcpuall{
  cpu {
    cpu.cfs_period_us = 100000;
    cpu.cfs_quota_us = 20000;
  }
}
" >> /etc/cgconfig.conf

配置应用使用cgroup的规则

/etc/cgrules.conf
echo -ne "
*:ffmpeg       cpu      limitcpu/
*:gcc        cpu   limitcpuall/
*:cpp       cpu   limitcpuall/
*:cc1        cpu   limitcpuall/
*:as       cpu   limitcpuall/
*:ld        cpu   limitcpuall/
*:genksyms  cpu   limitcpuall/
www   cpu   limitcpuall/
@root  cpu  limitcpuall/
" >> /etc/cgrules.conf

启用cgconfig和cgred服务

systemctl enable cgconfig
systemctl restart cgconfig
systemctl status cgconfig
systemctl enable cgred
systemctl restart cgred
systemctl status cgred

附送cpulimit限制cpu使用率的脚本

cpulimit脚本1: 30秒循环限制
while : ;do cpulimit -p `ps aux|awk '{if($3 > 80) print $2}'` -l 40;  sleep 30 ;done

cpulimit脚本2: 由crontab 定时循环限制
for pidnow in $(ps aux|awk '{if($3 > 80) print $2}') ;do if [[ "$pidnow" != "PID" ]] ; then  /usr/bin/cpulimit -p $pidnow -l 40 &  ; fi  done

参考文章
https://access.redhat.com/documentation/zh-cn/red_hat_enterprise_linux/7/html/resource_management_guide/index
https://www.digitalocean.com/community/tutorials/how-to-limit-resources-using-cgroups-on-centos-6

此处评论已关闭