代码改变世界

cpulimit work

2020-09-26 22:11  宋海宾  阅读(168)  评论(0编辑  收藏  举报

How it works

Note that you don't need to read this paragraph in order to use cpulimit, you can safely skip it if you are not interested in tweaking cpulimit.
So, you are curious to know the secrets of cpulimit :) Of course there is no secret if you are a C developer, but I will try to explain to everyone. The work of cpulimit is done all in userspace, so it doesn't interfere with the Linux scheduler. Basically, the target process, which you can specify by pid, name, or command line, is continuosly paused and resumed by sending it SIGSTOP and SIGCONT signals. Signals are sent by cpulimit in appropriate moments, based on the limit specified by user and the process statistics read from /proc.
[To be continued...]

System Requirements

cpulimit should run on every Linux 2.2 or greater. It has been reported by several users that cpulimit works fine even on SMP hardware, but consider that if you have more than one cpu there is a little difference in the meaning of cpu usage (see below).
If you can modify the source code of cpulimit to make it run in another OS, please notify me, so I can publish your code. I think that the only non-portable code is to iterate through the process list and get process statistics.

Instructions

Download last stable version from here or get the latest source code from Subversion repository with this command:

svn checkout https://cpulimit.svn.sourceforge.net/svnroot/cpulimit/trunk cpulimit

Then extract the source and compile with make:

tar zxf cpulimit-xxx.tar.gz
cd cpulimit-xxx
make

Executable file name is cpulimit. You may want to copy it in /usr/bin.

Examples of use

Limit the process 'bigloop' by executable name to 40% CPU:

cpulimit --exe bigloop --limit 40
cpulimit --exe /usr/local/bin/bigloop --limit 40

Limit a process by PID to 55% CPU:

cpulimit --pid 2960 --limit 55

Launch a process by command line and limit it to 40% (in development version only!):

cpulimit --limit 40 /etc/rc.d/rc.boinc start

Notes

If your machine has one processor you can limit the percentage from 0% to 100%, which means that if you set for example 50%, your process cannot use more than 500 ms of cpu time for each second. But if your machine has four processors, percentage may vary from 0% to 400%, so setting the limit to 200% means to use no more than half of the available power. In any case, the percentage is the same of what you see when you run top.

cpulimit should run at least with the same user running the controlled process. But it is much better if you run cpulimit as root, in order to have a higher priority and a more precise control.
Now cpulimit does limit also the children of the specified process. The code is still experimental, so let me know how it is.

cpulimit is written just for fun by Angelo Marletta.
Please send your feedback, bug reports, feature requests or just thanks:) to marlonx80 at hotmail dot com