process and cgroups

process and cgroups

Process and CGroups.

Using CGroups we can limit maximum amount of RAM and CPU can be consumed by a process.

Without creating a CGroup we can directly start a process with certain limits using systemd-run

sudo systemd-run --scope -p CPUQuota=10% -p MemoryMax=500M <process_name>

if want it more static, you can create a cgroup and configure limits then map the process ID to that Cgroup.

Create a new cgroup and set limits

laborant@ubuntu-01:~$ sudo mkdir /sys/fs/cgroup/my_custom_limit
laborant@ubuntu-01:~$ echo "+cpu +memory" | sudo tee /sys/fs/cgroup/cgroup.subtree_control
+cpu +memory
laborant@ubuntu-01:~$ cd /sys/fs/cgroup/my_custom_limit
laborant@ubuntu-01:my_custom_limit$ echo "500M" | sudo tee memory.max
500M
laborant@ubuntu-01:my_custom_limit$ echo "1
0000 100000" | sudo tee cpu.max # 10% of CPU
10000 100000

Memory.max vs .high

sudo tee memory.max -> the moment process reaches its limit, its get killed by OOM
sudo tee memory.high -> before this limit reached, memory utilizaition will be throttled to avoid killing.

Already running process

  • you can map a process to a cgroup which you created
laborant@ubuntu-01:my_custom_limit$ omnihog  > /dev/null & 
[1] 2545
laborant@ubuntu-01:my_custom_limit$ echo 2545 | sudo tee cgroup.procs
2545

Launch a shell so any new process under it get these limits applied

or you can launch new shell inside of that cgroup and then you can start the process, so that process will be applied those cgroup limits

laborant@ubuntu-01:my_custom_limit$ echo $$ | sudo tee cgroup.procs
1027
laborant@ubuntu-01:my_custom_limit$ omnihog 
[2026-10-29T12:25:30] Started a CPU hog
[2026-10-29T12:25:30] Started a CPU hog
[2026-10-29T12:25:30] Started a CPU hog
[2026-10-29T12:25:30] Started a CPU hog
[2026-10-29T12:25:31] Allocated 10 MB of memory
[2026-10-29T12:25:33] Allocated 10 MB of memory
[2026-10-29T12:25:35] Allocated 10 MB of memory
....
[2026-10-29T12:26:41] Allocated 10 MB of memory
Killed
laborant@ubuntu-01:my_custom_limit$ 

That’s it, and hope it helps.
Thank you.

0 comments:

Post a Comment