forgejo-runner-optimiser/identify-process-cgroup-by-pid.md
Manuel Ganter 5e470c33a5
All checks were successful
ci / build (push) Successful in 30s
feat(collector): group CPU and memory metrics by cgroup
Add cgroup-based process grouping to the resource collector. Processes are
grouped by their cgroup path, with container names resolved via configurable
process-to-container mapping.

New features:
- Read cgroup info from /proc/[pid]/cgroup (supports v1 and v2)
- Parse K8s resource notation (500m, 1Gi, etc.) for CPU/memory limits
- Group metrics by container using CGROUP_PROCESS_MAP env var
- Calculate usage percentages against limits from CGROUP_LIMITS env var
- Output cgroup metrics with CPU cores used, memory RSS, and percentages

Environment variables:
- CGROUP_PROCESS_MAP: Map process names to container names for discovery
- CGROUP_LIMITS: Define CPU/memory limits per container in K8s notation

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 14:50:36 +01:00

62 lines
1.2 KiB
Markdown

# Identify Process Cgroup by PID
## TL;DR
You can identify a process's cgroup by reading `/proc/<PID>/cgroup`.
## Outcome
Multiple methods to find which cgroup a process belongs to using its PID.
## Conversation
**Question:** Can I identify the process's cgroup by having its PID?
**Answer:** Yes, here are the main methods:
### Method 1: Read `/proc/<PID>/cgroup`
```bash
cat /proc/<PID>/cgroup
```
This shows all cgroup controllers the process belongs to. For example:
```
12:blkio:/user.slice
11:memory:/user.slice/user-1000.slice
...
0::/user.slice/user-1000.slice/session-1.scope
```
### Method 2: Using `ps` with format options
```bash
ps -o pid,cgroup -p <PID>
```
### Method 3: Using `systemd-cgls`
If you're on a systemd system:
```bash
systemd-cgls --unit <unit-name>
# or to see the whole tree
systemd-cgls
```
### Method 4: Check cgroup v2 unified hierarchy
On cgroup v2 systems, check:
```bash
cat /proc/<PID>/cgroup
# Output will look like: 0::/user.slice/user-1000.slice/session-1.scope
```
The path after `::` is the cgroup path under `/sys/fs/cgroup/`.
### Quick one-liner
```bash
cat /proc/self/cgroup # For current shell
cat /proc/$$/cgroup # Also current shell
cat /proc/1234/cgroup # For PID 1234
```