linux-sysprog · intermediate · ~10 min

Compute a cgroup v2 cpu.max line

cgroup v2 cpu.max format.

Challenge

Given a desired CPU share as a fraction (e.g. 0.5 for half a core, 2.0 for two cores) and a period in microseconds (default 100000), implement int format_cpu_max(double cores, int period_us, char *out, int cap).

Output format: "%lld %d" where the first number is cores * period_us (rounded to nearest), the second is period_us. Returns bytes written (excluding NUL), or -1 if cap too small.

Special case: cores < 0 is invalid; return -1.

Why this matters

cgroup v2's cpu.max is the standard CPU cap. The format is 'quota period' in microseconds. Compose it correctly the first time.

Input format

cores fraction + period + buffer.

Output format

bytes written or -1.

Constraints

Use snprintf.

Starter code

#include <stddef.h>
int format_cpu_max(double cores, int period_us, char *out, int cap) { /* TODO */ (void)cores; (void)period_us; (void)out; (void)cap; return -1; }

Common mistakes

Outputting cores instead of cores * period_us.

Edge cases to handle

cores == 0 (no CPU); cores == 1.0 (one core); fractional like 0.5.

Complexity

O(1).

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.