1# Control Groups {#sec-cgroups} 2 3To keep track of the processes in a running system, systemd uses 4*control groups* (cgroups). A control group is a set of processes used 5to allocate resources such as CPU, memory or I/O bandwidth. There can be 6multiple control group hierarchies, allowing each kind of resource to be 7managed independently. 8 9The command `systemd-cgls` lists all control groups in the `systemd` 10hierarchy, which is what systemd uses to keep track of the processes 11belonging to each service or user session: 12 13```ShellSession 14$ systemd-cgls 15├─user 16│ └─eelco 17│ └─c1 18│ ├─ 2567 -:0 19│ ├─ 2682 kdeinit4: kdeinit4 Running... 20│ ├─ ... 21│ └─10851 sh -c less -R 22└─system 23 ├─httpd.service 24 │ ├─2444 httpd -f /nix/store/3pyacby5cpr55a03qwbnndizpciwq161-httpd.conf -DNO_DETACH 25 │ └─... 26 ├─dhcpcd.service 27 │ └─2376 dhcpcd --config /nix/store/f8dif8dsi2yaa70n03xir8r653776ka6-dhcpcd.conf 28 └─ ... 29``` 30 31Similarly, `systemd-cgls cpu` shows the cgroups in the CPU hierarchy, 32which allows per-cgroup CPU scheduling priorities. By default, every 33systemd service gets its own CPU cgroup, while all user sessions are in 34the top-level CPU cgroup. This ensures, for instance, that a thousand 35run-away processes in the `httpd.service` cgroup cannot starve the CPU 36for one process in the `postgresql.service` cgroup. (By contrast, it 37they were in the same cgroup, then the PostgreSQL process would get 381/1001 of the cgroup's CPU time.) You can limit a service's CPU share in 39`configuration.nix`: 40 41```nix 42{ 43 systemd.services.httpd.serviceConfig.CPUShares = 512; 44} 45``` 46 47By default, every cgroup has 1024 CPU shares, so this will halve the CPU 48allocation of the `httpd.service` cgroup. 49 50There also is a `memory` hierarchy that controls memory allocation 51limits; by default, all processes are in the top-level cgroup, so any 52service or session can exhaust all available memory. Per-cgroup memory 53limits can be specified in `configuration.nix`; for instance, to limit 54`httpd.service` to 512 MiB of RAM (excluding swap): 55 56```nix 57{ 58 systemd.services.httpd.serviceConfig.MemoryLimit = "512M"; 59} 60``` 61 62The command `systemd-cgtop` shows a continuously updated list of all 63cgroups with their CPU and memory usage.