Add the process id to the desired cgroup’s cgroup.procs file.


# create cgroup
sudo mkdir /sys/fs/cgroup/testgroup
# enable cpu interface
echo "+cpu" | sudo tee -a /sys/fs/cgroup/cgroup.subtree_control 
# enable cpuset interface
echo "+cpuset" | sudo tee -a /sys/fs/cgroup/cgroup.subtree_control 
# add current process to cgroup
echo "$$" | sudo tee -a /sys/fs/cgroup/testgroup/cgroup.procs 

We first check to see what cgroup our current session belongs to by reading /proc/self/cgroup. In this case belong to the cgroup /user.slice/user-1000.slice/user@1000.service/app.slice/app-org.gnome.Terminal.slice/vte-spawn-21dfc4b3-8145-4982-a7df-e3446806ad94.scope. We can use this to determine which controllers are enabled. In this case only memory and pids controllers are enabled.


cat /proc/self/cgroup 
# 0::/user.slice/user-1000.slice/user@1000.service/app.slice/app-org.gnome.Terminal.slice/vte-spawn-21dfc4b3-8145-4982-a7df-e3446806ad94.scope

cat /sys/fs/cgroup/user.slice/user-1000.slice/user@1000.service/app.slice/app-org.gnome.Terminal.slice/vte-spawn-21dfc4b3-8145-4982-a7df-e3446806ad94.scope/cgroup.controllers
# memory pids

For now we’re just going to create a new cgroup, enable the desired controllers, and then add our session to the cgroup.

We can create a test cgroup with mkdir. The kernel will create all the necessary files for us. You must be a privileged user to create the cgroup.


sudo mkdir /sys/fs/cgroup/testgroup

After we create the test cgroup we will enable the cpu and cpuset controllers for subtrees by adding entries for both in the cgroup.subtree_control file. This allows us to specify resources for cpu and cpuset in our test cgroup.


echo "+cpu" | sudo tee -a /sys/fs/cgroup/cgroup.subtree_control 
#+cpu
echo "+cpuset" | sudo tee -a /sys/fs/cgroup/cgroup.subtree_control 
#+cpuset

Lastly, we add our current session to our cgroup, testgroup. Now any process that we create from this session will belong to testgroup by default and will inherit the resource limits that we specified. For example we can limit our cgroup to just 6 cpus worth of time by configuring a cpu quota of 600000 in cpu.max.


echo "$$" | sudo tee -a /sys/fs/cgroup/testgroup/cgroup.procs 
# 12390
cat /proc/self/cgroup 
# 0::/testgroup
cat /sys/fs/cgroup/testgroup/cpu.max
# max 100000
echo "600000" | sudo tee -a /sys/fs/cgroup/testgroup/cpu.max
# 600000
cat /sys/fs/cgroup/testgroup/cpu.max
# 600000 100000