Linux Control Groups

Using cgroups you can limit resource usage of processes , for example if you have a web server and you want limit its memory usage to 1GB its very easy to do with cgroups.

This is also a basic building block for containers

First we need to install some tools (in my example im using Ubuntu)

# sudo apt install cgmanager
# sudo apt install cgroup-tools

cgroup and cgroup2 are file systems in linux. In the kernel code you can find it in /kernel/cgroup/cgroup.c and from user perspective if you do:

# cat /proc/filesystems

also running a mount command:

# mount

cgroup on /sys/fs/cgroup/systemd type cgroup (rw,nosuid,…)
cgroup on /sys/fs/cgroup/memory type cgroup (rw,nosuid,…)
cgroup on /sys/fs/cgroup/blkio type cgroup (rw,nosuid,…)


Simple example:

First we create a new group, we want to limit memory usage:

# sudo cgm create memory myg

it will create the following folder : /sys/fs/cgroup/memory/user.slice/myg/

Now we can change permission using:

# sudo cgm chown memory myg 1000 1000
# sudo chown -R developer:developer /sys/fs/cgroup/memory/user.slice/myg/*

To limit the memory of the group to 20MB:

# echo "20000000"> /sys/fs/cgroup/memory/user.slice/myg/memory.limit_in_bytes

Code example of memory usage:


void main(void)
            int i=0;
            int *p;
                        p= (int *)malloc(1000000);
                                    printf("1MB allocated i=%d\n",i);
                                    printf("out of memory\n");


if you run it as is you will see the output until the system is out of memory

to control the memory usage we need to move it to the above cgroup:

# echo [pid] > /sys/fs/cgroup/memory/user.slice/myg/cgroup.procs
# echo [pid] > /sys/fs/cgroup/memory/user.slice/myg/cgroup.procs


you will see the process killed after the limit is reached

Freezer cgroup

Another example is freezing control group. Any task in that group can be suspended


# mkdir /sys/fs/cgroup/freezer/0
# echo [pid]>/sys/fs/cgroup/freezer/0/tasks

# echo FROZEN > /sys/fs/cgroup/freezer/0/freezer.state
# echo THAWED > /sys/fs/cgroup/freezer/0/freezer.state



1 thought on “Linux Control Groups

  1. […] example to understand the concept. to implement a full container you need also to add capabilities, control groups and […]

Comments are closed.