Lesson 11 of 15
Ring Buffer
The Ring Buffer
A ring buffer (circular buffer) is the data structure at the heart of Linux pipes. It is a fixed-size array where write and read positions wrap around:
buf: [ h | e | l | l | o | | | ]
↑ ↑
head tail
(read here) (write here)
- write: store byte at
tail, advancetail = (tail + 1) % size - read: load byte from
head, advancehead = (head + 1) % size - full:
count == size - empty:
count == 0
Your Implementation
#define RB_SIZE 8
typedef struct {
char buf[RB_SIZE];
int head, tail, count;
} RingBuf;
int rb_write(RingBuf *rb, char c) {
if (rb->count == RB_SIZE) return 0;
rb->buf[rb->tail] = c;
rb->tail = (rb->tail + 1) % RB_SIZE;
rb->count++;
return 1;
}
int rb_read(RingBuf *rb, char *c) {
if (rb->count == 0) return 0;
*c = rb->buf[rb->head];
rb->head = (rb->head + 1) % RB_SIZE;
rb->count--;
return 1;
}
Your Task
Implement rb_write and rb_read. Also write rb_drain that reads and prints all remaining bytes.
TCC compiler loading...
Loading...
Click "Run" to execute your code.