How to restrict the CPU and Memory Usage of a process on CentOS?
To restrict CPU and memory usage of a process on CentOS, you can use cgroups
(Control Groups) and the related utilities that come with the libcgroup
package.
Here's a basic overview of how to use cgroups
to limit CPU and memory usage:
1. Install libcgroup
tools:
sudo yum install libcgroup libcgroup-tools
2. Start and enable the cgconfig
service:
sudo systemctl start cgconfig
sudo systemctl enable cgconfig
3. Create a Control Group:
For this example, we'll create a control group named limited_group
that restricts CPU and memory.
First, configure the CPU:
sudo cgcreate -g cpu:/limited_group
Now, set the CPU limit. For instance, to allocate only 20% of the CPU to limited_group
:
echo 200000 > /sys/fs/cgroup/cpu/limited_group/cpu.cfs_quota_us
echo 1000000 > /sys/fs/cgroup/cpu/limited_group/cpu.cfs_period_us
Next, configure memory. Create the memory group:
sudo cgcreate -g memory:/limited_group
To limit memory usage to, for example, 500MB:
echo 500M > /sys/fs/cgroup/memory/limited_group/memory.limit_in_bytes
4. Assign a Process to the Control Group:
To add a process to this group, you need the PID of the process. For example, if the PID is 12345
:
echo 12345 > /sys/fs/cgroup/cpu/limited_group/tasks
echo 12345 > /sys/fs/cgroup/memory/limited_group/tasks
5. Make the configuration persistent across reboots:
To make these configurations persistent, you would typically configure the /etc/cgconfig.conf
and /etc/cgrules.conf
files.
In /etc/cgconfig.conf
:
group limited_group {
cpu {
cpu.cfs_quota_us = 200000;
cpu.cfs_period_us = 1000000;
}
memory {
memory.limit_in_bytes = 500M;
}
}
In /etc/cgrules.conf
:
*:myuser cpu,memory limited_group/
Replace myuser
with the name of the user whose processes you want to restrict.
Finally, restart the cgconfig
service:
sudo systemctl restart cgconfig
Note: These are just basic configurations. Cgroups offer much more advanced controls, and it's essential to test any configurations in a non-production environment first. Adjustments might be required based on specific needs and system behavior.