Linux 101 : Introduction to Control Groups (Cgroups)


Cgroups organize processes in groups and allocates a share of the resources (CPU, RAM, Network,...) to them.
We can limit for example for a group of processes their memory consumption or their CPU use.
We could also use cgroup to stop or restart a group of processes.

Cgroups are made up of:
  • the core which manages the cgroup tree.
  • The controllers that manage the sharing of the resources through the cgroup tree.
Cgoups are organized into a tree structure. 
Each process can only belong to one cgroup
Children cgoups get their attributes from their parents. To be able to view the cgroups hierarchy we use the command:

Above you can see a snippet of the cgroup tree.
We have a different hierarchy for each subsystem(controller) like  the CPU, the memory, the RAM and the network resources,....
Cgroup is a pseudo-filesystem (cgroupfs) that can be mounted like any other filesystem:

Creating new cgroups:

We can create a child cgroup under the root cgroup using the mkdir commands, we can also remove a cgroup  when no procees lives inside anymore using the rm command. 

To which cgroup a process belongs to?

We use the below command to display the cgroup a process belongs to:

Example (Limiting memory):

We create a cgroup named cgroup_A below the memory subsystem /sys/fs/cgroup/memory as we want to limit the memory usage for a certain process:

In order to limit the memory used by a process in cgroupA, we need to modify the memory.limit_in_bytes file.
We will limit the memory usage for the cgroup "cgroup_A" and anything below it in the hierarchy to 200MB

Now that we have set the limit for the cgroup "cgroup_A", we need to move the process to the cgroup_A

There are other subsystems other than the memory (in the above example) that we could use to limit the resources for processes, for example :
  • blkio / io (cgroups-V2) : Sets the limits of output/input for block devices
  • pid : to limit the number of processes and their children.


Leave as a comment: