linux-sysprog · intermediate · ~10 min

Compute a cgroup v2 cpu.max line

cgroup v2 cpu.max format.

Challenge

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.

Task

Implement int format_cpu_max(double cores, int period_us, char *out, int cap) that writes the cpu.max line.

Input

  • 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.

Output

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.

Example

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)

Edge cases

  • cores < 0: return -1.
  • A buffer too small for the full line: return -1.
  • cores == 0 produces a quota of 0.

Rules

  • The first number is cores * period_us rounded, not cores itself. Use snprintf.

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 (a CPU-share fraction), period_us (microseconds), and an output buffer out of size cap.

Output format

Writes '<round(cores*period_us)> ' into out; returns bytes written, or -1 if cap is too small or cores < 0.

Constraints

Quota is cores*period_us rounded to nearest. Use snprintf; cores < 0 or truncation returns -1.

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.