A key press raises an interrupt. The handler must be quick, so it only stores the character in a small ring buffer in the kernel. The program reads the characters later, when it asks. If the buffer is full when a key arrives, the character is lost.
What to build
Simulate the keyboard handler and a program that reads from the buffer.
Requirements
- The buffer holds up to
Ncharacters, first in, first out, and starts empty. key c: the interrupt handler stores the charactercif there is room; if the buffer is full the character is dropped and counted.read: the program takes the oldest character and prints it on its own line; if the buffer is empty it printsempty.- At the end print
dropped: Dandleft: L, the number of dropped characters and the number still in the buffer.
Input
The first line has N (1 ≤ N ≤ 8) and q (1 ≤ q ≤ 40). Then q events, one per line: key c (a single letter or digit) or read.
Output
One line for each read, then dropped: D and left: L.
Constraints
Characters are letters and digits only.
Example
Input:
3 7
key a
key b
read
key c
key d
key e
read
Output:
a
b
dropped: 1
left: 2
Why it works
The handler never waits: when the buffer is full it just drops the key, because blocking inside an interrupt handler would freeze the whole machine. The ring buffer lets the fast interrupt side and the slow program side work at their own speed.
Examples
3 7 key a key b read key c key d key e read
a b dropped: 1 left: 2
2 3 read key x read
empty x dropped: 0 left: 0
Hints
Hint 1
Use an array of N chars as a circular queue with in, out and count, like the bounded buffer.
Hint 2
Read the event word, then for key read one character with scanf(" %c", &c).
Hint 3
A key into a full buffer is dropped: count it and change nothing else.
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
#include <string.h>
int main(void) {
int cap, q, in = 0, out = 0, count = 0, dropped = 0;
char buffer[8], word[8], c;
scanf("%d %d", &cap, &q);
for (int i = 0; i < q; i++) {
scanf("%7s", word);
if (strcmp(word, "key") == 0) {
scanf(" %c", &c);
if (count == cap) {
dropped++;
} else {
buffer[in] = c;
in = (in + 1) % cap;
count++;
}
} else {
if (count == 0) {
printf("empty\n");
} else {
printf("%c\n", buffer[out]);
out = (out + 1) % cap;
count--;
}
}
}
printf("dropped: %d\n", dropped);
printf("left: %d\n", count);
return 0;
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step