1 cpulimitコマンドとは?
NICE値やスケジューリングポリシーを変更せず、プロセスのCPU使用率を制限することができるコマンドです。以下にGitHub - opsengine/cpulimit: CPU usage limiter for Linuxからの抜粋を示します。
Cpulimit is a tool which limits the CPU usage of a process (expressed in percentage, not in CPU time). It is useful to control batch jobs, when you don't want them to eat too many CPU cycles. The goal is prevent a process from running for more than a specified time ratio. It does not change the nice value or other scheduling priority settings, but the real CPU usage. Also, it is able to adapt itself to the overall system load, dynamically and quickly. The control of the used CPU amount is done sending SIGSTOP and SIGCONT POSIX signals to processes. All the children processes and threads of the specified process will share the same percentage of CPU.
2 検証環境
CentOS版数は以下のとおりです。
[root@server ~]# cat /etc/centos-release CentOS Linux release 7.9.2009 (Core)
カーネル版数は以下のとおりです。
[root@server ~]# uname -r 3.10.0-1160.el7.x86_64
3 インストール方法
cpulimitパッケージは、epelリポジトリにあるので、まず、epel-releaseパッケージをインストールします。
[root@server ~]# yum -y install epel-release
次に、cpulimitパッケージをインストールします。
[root@server ~]# yum -y install cpulimit
4 オプション一覧
オプションは以下のとおりです。
[root@server ~]# cpulimit -h Usage: cpulimit [OPTIONS...] TARGET OPTIONS -l, --limit=N percentage of cpu allowed from 0 to 400 (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) Report bugs to <marlonx80@hotmail.com>.
5 CPU使用率の制限方法
stress-ngコマンドを使って、CPU使用率が10%のプロセスを1つ生成します。
なお、stress-ngコマンドのインストール方法、使い方は、stress-ngコマンドの使い方 - hana_shinのLinux技術ブログを参照してください。
[root@server ~]# stress-ng -k -c 1 -l 10 -q & [1] 1527
プロセスの状態を確認します。親プロセス(PID1527)はwaitシステムコールを実行して、子プロセス(PID1528)の終了を待っています。そのため、CPU使用率が0%であることがわかります。なお、do_wait関数は、waitシステムコールの延長で呼び出すカーネル関数です。一方、子プロセスはCPU使用率が約12%であることがわかります。なお、psコマンドの使い方は、psコマンドの使い方 - hana_shinのLinux技術ブログを参照してください。
[root@server ~]# ps -C stress-ng -o comm,pid,ppid,%cpu,wchan COMMAND PID PPID %CPU WCHAN stress-ng 1527 1114 0.0 do_wait stress-ng 1528 1527 11.7 -
cpulimitコマンドを使って、子プロセスのCPU使用率を5%に制限してみます。
[root@server ~]# cpulimit -p 1528 -l 5 Process 1528 found
もう1つターミナルを開いて、CPU使用率を確認します。指定したCPU使用率にすぐになるのではなく、徐々に指定したCPU使用率に下がっていくのがわかります。
[root@server ~]# ps -C stress-ng -o comm,pid,ppid,%cpu COMMAND PID PPID %CPU stress-ng 1527 1114 0.0 stress-ng 1528 1527 8.6
CPU使用率を確認します。私の環境では、10分程度経過したあと、子プロセスのCPU使用率が約5%になりました。
[root@server ~]# ps -C stress-ng -o comm,pid,ppid,%cpu COMMAND PID PPID %CPU stress-ng 1527 1114 0.0 stress-ng 1528 1527 4.9
Z 参考情報
私が業務や記事執筆で参考にした書籍を以下のページに記載します。
Linux技術のスキルアップをしよう! - hana_shinのLinux技術ブログ