linux-sysprog · intermediate · ~15 min

Lowest free file descriptor

Model the fd-allocation rule.

Challenge

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.

Task

Implement int lowest_free_fd(const int *open_fds, int n) that returns the smallest non-negative integer not present in open_fds.

Input

  • open_fds: array of n currently-open descriptor numbers (any order, non-negative).
  • n: array length (may be 0).

Output

The smallest integer >= 0 that does not appear in open_fds.

Example

lowest_free_fd([0,1,2], 3)   ->   3
lowest_free_fd([0,2,3], 3)   ->   1

Edge cases

  • n == 0: return 0.
  • A gap below the maximum (e.g. missing 1) returns that gap.

Input format

open_fds: array of n non-negative descriptor numbers; n: its length (>= 0).

Output format

Smallest non-negative integer not in the array.

Constraints

Descriptors are non-negative; the array may be empty or have gaps.

Starter code

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.