Systemd – How to Limit CPU Usage with Systemd-Run

cgroupscpulimitsystemdsystemd-run

I have a buggy program which uses 100% CPU even when it's idle. Since fixing it isn't practical at the moment, I'd like to just limit it to be able to use no more than 10% CPU. However no matter what I do, the process always chews up 100% of one CPU.

I found instructions on the Arch Wiki that tell me to create a file containing this:

# cpulimit.slice
[Slice]
CPUQuota=10%

Apparently I can then launch a shell using these limits, like this:

systemd-run --slice=cpulimit.slice --uid=myuser --shell

This seems to work and after entering in my sudo password I get a shell, so I run a simple test that will use 100% CPU and I can stop with Ctrl+C:

while true; do true; done

I expect this to use no more than 10% CPU since it's running inside the slice, however it always uses 100% CPU!

What am I doing wrong?

Best Answer

Just discovered the problem. The .slice file must be placed in /etc/systemd/system/ and you have to run systemctl daemon-reload first. Then it all works.

Unfortunately the systemd-run command doesn't give you any error messages if you use an invalid --slice parameter, it just creates a new slice with no additional restrictions, called whatever name you supplied.

Related Question