linux-sysprog · intermediate · ~15 min
Track pipe occupancy as a producer/consumer count.
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.
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.
ops: a string of 'w' and 'r' characters.The number of bytes remaining (always >= 0).
pipe_bytes_available("wwr") -> 1
pipe_bytes_available("rww") -> 2 (leading read is a no-op)
pipe_bytes_available("wr") -> 0
ops: string of 'w' (write one byte) and 'r' (read one byte).
Bytes remaining in the pipe (>= 0).
A read on an empty pipe is a no-op; the count never goes negative.
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.