linux-sysprog · intermediate · ~15 min

Bytes left in a pipe

Track pipe occupancy as a producer/consumer count.

Challenge

A pipe is a bounded FIFO of bytes. Simulate one from an operation string and report how many bytes are still buffered at the end.

Task

Implement int pipe_bytes_available(const char *ops) that replays ops and returns the byte count left in the pipe. Each 'w' writes one byte (count +1); each 'r' reads one byte (count -1), but a read on an empty pipe is a no-op.

Input

  • ops: a string of 'w' and 'r' characters.

Output

The number of bytes remaining (always >= 0).

Example

pipe_bytes_available("wwr")   ->   1
pipe_bytes_available("rww")   ->   2   (leading read is a no-op)
pipe_bytes_available("wr")    ->   0

Edge cases

  • Read on an empty pipe: ignored, count stays 0.

Input format

ops: string of 'w' (write one byte) and 'r' (read one byte).

Output format

Bytes remaining in the pipe (>= 0).

Constraints

A read on an empty pipe is a no-op; the count never goes negative.

Starter code

int pipe_bytes_available(const char *ops) {
    /* TODO */
    return 0;
}

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