linux-sysprog · intermediate · ~15 min
Model the fd-allocation rule.
When a process opens a file, the kernel assigns the lowest unused descriptor number. This models that allocation rule on a snapshot of the table.
Implement int lowest_free_fd(const int *open_fds, int n) that returns the smallest non-negative integer not present in open_fds.
open_fds: array of n currently-open descriptor numbers (any order, non-negative).n: array length (may be 0).The smallest integer >= 0 that does not appear in open_fds.
lowest_free_fd([0,1,2], 3) -> 3
lowest_free_fd([0,2,3], 3) -> 1
n == 0: return 0.open_fds: array of n non-negative descriptor numbers; n: its length (>= 0).
Smallest non-negative integer not in the array.
Descriptors are non-negative; the array may be empty or have gaps.
int lowest_free_fd(const int *open_fds, int n) {
/* TODO */
return 0;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.