linux-sysprog · beginner · ~15 min

Count open descriptors

Scan a descriptor table.

Challenge

A process keeps a fixed-size descriptor table where each slot is either a live descriptor or -1 for a closed slot. Count the live ones.

Task

Implement int count_open_fds(const int *table, int n) that returns how many of the n slots are open (not equal to -1).

Input

  • table: array of n slots; each is a descriptor number or -1 (closed).
  • n: number of slots.

Output

The count of slots whose value is not -1.

Example

count_open_fds([3,-1,5,-1], 4)   ->   2
count_open_fds([-1,-1], 2)       ->   0

Edge cases

  • All slots -1: return 0.

Input format

table: array of n slots, each a descriptor or -1; n: slot count.

Output format

Number of slots not equal to -1.

Constraints

-1 marks a closed slot; any other value is an open descriptor.

Starter code

int count_open_fds(const int *table, int n) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.