linux-sysprog · intermediate · ~10 min
cgroup v2 cpu.max format.
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.
cgroup v2's cpu.max is the standard CPU cap. The format is 'quota period' in microseconds. Compose it correctly the first time.
cores fraction + period + buffer.
bytes written or -1.
Use snprintf.
#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.