cpulimit 命令的工作原理是为进程预设一个 cpu 占用率门限,并实时监控进程是否超出此门限,若超出则让该进程暂停运行一段时间。cpulimit 使用 SIGSTOP 和 SIGCONT 这两个信号来控制进程。它不会修改进程的 nice 值,而是通过监控进程的 cpu 占用率来做出动态调整。

cpulimit 的优势是可以控制进程的cpu使用率的上限值。但与 nice 相比也有缺点,那就是即使 cpu 是空闲的,进程也不能完全使用整个 cpu 资源。

在 CentOS 上,可以用下面的方法来安装它:

wget -O cpulimit.zip https://github.com/opsengine/cpulimit/archive/master.zip
unzip cpulimit.zip
cd cpulimit-master
make
sudo cp src/cpulimit /usr/bin

上面的命令行,会先从从 GitHub 上将源码下载到本地,然后再解压、编译、并安装到 /usr/bin 目录下。

cpulimit 的使用方式和 nice 命令类似,但是需要用户使用 -l 选项显式地定义进程的 cpu 使用率上限值。举例说明:

cpulimit -l 50 matho-primes 0 9999999999 > /dev/null &

cpulimit

从上面的例子可以看出 matho-primes 只使用了50%的 cpu 资源,剩余的 cpu 时间都在 idle。

cpulimit 其他实例:

cpulimit -e httpd --limit 40 #限制httpd(进程名)的cpu使用率为40%
cpulimit -e /usr/local/bin/httpd --limit 40
cpulimit -p 2960 -l 55 #限制pid为2960的进程的CPU占用为55%

使用帮助:
Usage: cpulimit [OPTIONS...] TARGET
OPTIONS
-l, --limit=N percentage of cpu allowed from 0 to 3200 (required)
-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)
-e, --exe=FILE name of the executable program file or path name
COMMAND [ARGS] run this command and limit it (implies -z)

参考:https://linux.cn/article-4742-1.html

标签: 管理维护, Linux

添加新评论