How to Configure Linux cgroups v2 to Restrict Process Resource Usage

Introduction

Control Groups (cgroups) are a powerful Linux kernel feature used to allocate, restrict, and monitor system resources (CPU, memory, disk I/O) among processes. cgroups v2 provides a unified hierarchy, simplifying management compared to v1. This guide demonstrates how to create a cgroup, set memory and CPU limits, and assign processes to it using standard system utilities.

Prerequisites

Ensure your Linux distribution uses cgroups v2. Most modern distributions (Ubuntu 22.04+, Fedora, Debian 11+) default to v2. Verify by running:

mount | grep cgroup2

You should see an output indicating cgroup2 is mounted at /sys/fs/cgroup. You must run these commands as the root user.

Step 1: Create a New cgroup

Creating a cgroup in v2 is as simple as creating a directory within the cgroup filesystem. Let’s create a group named restricted_tasks:

mkdir /sys/fs/cgroup/restricted_tasks

The kernel will automatically populate this directory with control files like cgroup.procs, memory.max, and cpu.max.

Step 2: Restrict Memory Usage

To prevent processes in this group from consuming too much RAM, configure the memory.max file. For example, to limit the group to 500 Megabytes:

echo 500M > /sys/fs/cgroup/restricted_tasks/memory.max

If processes in this cgroup exceed 500MB, the Linux OOM (Out of Memory) killer will terminate them.

Step 3: Restrict CPU Usage

CPU limits are defined using bandwidth control in cpu.max. The format is [quota] [period]. To limit the group to 50% of a single CPU core (50,000 microseconds per 100,000 microsecond period):

echo "50000 100000" > /sys/fs/cgroup/restricted_tasks/cpu.max

Step 4: Assign a Process to the cgroup

To apply these restrictions, you must write the Process ID (PID) to the cgroup.procs file. For example, to restrict a running process with PID 1234:

echo 1234 > /sys/fs/cgroup/restricted_tasks/cgroup.procs

Any child processes spawned by PID 1234 will automatically inherit these cgroup limits. To remove the cgroup when finished, kill the assigned processes and remove the directory: rmdir /sys/fs/cgroup/restricted_tasks.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.