Cgroups (control groups) are a Linux kernel feature that allows you to control and limit the resources (CPU, memory, I/O) that processes can use. This becomes crucial for system stability, especially when working with resource-hungry applications, containers, or virtual machines.

How Cgroups Work

Cgroups create hierarchical groups where processes can be restricted or monitored in terms of resource consumption. Each resource type (CPU, memory, etc.) has a corresponding controller that manages the behavior of processes within that group.

Practical Example

Imagine you're dealing with a process consuming excessive CPU and memory, affecting other processes on your server. With cgroups, you can limit this behavior:

  1. Create a Cgroup: Manually create a directory for your cgroup in the cgroupfs filesystem:
    mkdir /sys/fs/cgroup/hog_pen
  2. Set CPU and Memory Limits: You can limit CPU usage to 50% and memory usage to 100MB by writing values to the appropriate files:
    echo "50000 100000" > /sys/fs/cgroup/hog_pen/cpu.max echo "100M" > /sys/fs/cgroup/hog_pen/memory.max
  3. Add Processes to the Cgroup: Move an existing process into the cgroup by writing its PID to cgroup.procs:
    echo $(pgrep -xo hog) >> /sys/fs/cgroup/hog_pen/cgroup.procs

This ensures the process is restricted by the limits you've set. For more convenience, you can use tools like libcgroup or systemd-run to create and manage cgroups with fewer manual steps.

Tools for Managing Cgroups

While you can manage cgroups manually through the cgroupfs, using higher-level tools simplifies the process:

  • cgcreate and cgexec: Tools from the libcgroup package make cgroup management easier with commands like cgcreate (to create a cgroup) and cgexec (to execute a process inside a cgroup).
  • systemd-run: With systemd, managing resource limits is even easier. For instance, you can limit CPU and memory for a process by running:
    systemd-run -u hog -p CPUQuota=50% -p MemoryMax=100M ~/hog

Conclusion

Cgroups offer powerful control over system resources, making them essential for both production environments (e.g., Docker containers, Kubernetes pods) and development. By mastering cgroups, you can prevent rogue processes from overwhelming your system while ensuring resource fairness across applications​.

You can read more about Cgroups here:
https://docs.kernel.org/admin-guide/cgroup-v2.html
https://man7.org/linux/man-pages/man7/cgroups.7.html
https://www.freedesktop.org/software/systemd/man/latest/systemd-run.html
https://wiki.archlinux.org/title/Cgroups

The link has been copied!