linux-sysprog · intermediate · ~10 min
cgroup v2 cpu.max format.
Build the cpu.max line that a cgroup v2 controller expects: a quota and a period, both in microseconds. This formats a string — it does not touch any real cgroup.
Implement int format_cpu_max(double cores, int period_us, char *out, int cap) that writes the cpu.max line.
cores: the desired CPU share (e.g. 0.5 for half a core, 2.0 for two cores).period_us: the scheduling period in microseconds (commonly 100000).out, cap: destination buffer and its size.Writes "<quota> <period_us>" into out, where quota = round(cores * period_us) (nearest integer). Returns the number of bytes written (excluding the NUL), or -1 if out is too small or cores < 0.
format_cpu_max(1.0, 100000, out, 64) -> out = "100000 100000"
format_cpu_max(0.5, 100000, out, 64) -> out = "50000 100000"
format_cpu_max(2.0, 50000, out, 64) -> out = "100000 50000"
format_cpu_max(-1.0, 100000, out, 64) -> -1 (negative cores)
format_cpu_max(1.0, 100000, out, 5) -> -1 (buffer too small)
cores < 0: return -1.-1.cores == 0 produces a quota of 0.cores * period_us rounded, not cores itself. Use snprintf.cgroup v2's cpu.max is the standard CPU cap. The format is 'quota period' in microseconds. Compose it correctly the first time.
cores (a CPU-share fraction), period_us (microseconds), and an output buffer out of size cap.
Writes '<round(cores*period_us)>
Quota is cores*period_us rounded to nearest. Use snprintf; cores < 0 or truncation returns -1.
#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; }
Outputting cores instead of cores * period_us.
cores == 0 (no CPU); cores == 1.0 (one core); fractional like 0.5.
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.