linux-sysprog · beginner · ~15 min

Would the write block?

Reason about pipe back-pressure.

Challenge

A pipe buffer has a fixed capacity; when it fills up, write() blocks until a reader drains it (back-pressure). Decide whether the next write would block.

Task

Implement int write_would_block(int inflight, int capacity, int n) that returns 1 if adding n bytes to the inflight already buffered would exceed capacity, else 0.

Input

  • inflight: bytes currently buffered.
  • capacity: total buffer size.
  • n: bytes about to be written.

Output

1 if inflight + n > capacity, else 0.

Example

write_would_block(10, 64, 20)   ->   0
write_would_block(60, 64, 10)   ->   1
write_would_block(60, 64, 4)    ->   0   (exactly fills it)

Edge cases

  • Filling exactly to capacity does not block (return 0).

Input format

inflight: buffered bytes; capacity: buffer size; n: bytes to write.

Output format

1 if inflight + n > capacity, else 0.

Constraints

Filling exactly to capacity does not block.

Starter code

int write_would_block(int inflight, int capacity, int n) {
    /* TODO */
    return 0;
}

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