feat: Add read timeout and error handling.

This commit is contained in:
jmug
2026-10-09 17:29:18 -07:00
parent 10691f8962
commit 908eb1ef1c
+31 -5
View File
@@ -1,38 +1,64 @@
/*** includes ***/
#include <ctype.h> #include <ctype.h>
#include <errno.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <termios.h> #include <termios.h>
#include <unistd.h> #include <unistd.h>
/*** data ***/
struct termios orig_termios; struct termios orig_termios;
/*** terminal ***/
void die(const char* s) {
perror(s);
exit(1);
}
void disableRawMode() { void disableRawMode() {
tcsetattr(STDIN_FILENO, TCSAFLUSH, &orig_termios); if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &orig_termios) == -1)
die("tcsetattr");
} }
void enableRawMode() { void enableRawMode() {
tcgetattr(STDIN_FILENO, &orig_termios); if (tcgetattr(STDIN_FILENO, &orig_termios) == -1)
die("tcgetattr");
atexit(disableRawMode); atexit(disableRawMode);
struct termios raw = orig_termios; struct termios raw = orig_termios;
raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON); raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
raw.c_oflag &= ~(OPOST); raw.c_oflag &= ~(OPOST);
raw.c_cflag |= (CS8); raw.c_cflag |= (CS8);
raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG); raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw); // Sets timeouts for read()
raw.c_cc[VMIN] = 0;
raw.c_cc[VTIME] = 1;
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1)
die("tcsetattr");
} }
/*** init ***/
int main() { int main() {
enableRawMode(); enableRawMode();
char c; while(1) {
while(read(STDIN_FILENO, &c, 1) == 1 && c != 'q') { char c = '\0';
if (read(STDIN_FILENO, &c, 1) == -1 && errno != EAGAIN)
die("read");
if (iscntrl(c)) { if (iscntrl(c)) {
printf("%d\r\n", c); printf("%d\r\n", c);
} else { } else {
printf("%d ('%c')\r\n", c, c); printf("%d ('%c')\r\n", c, c);
} }
if (c == 'q')
break;
} }
return 0; return 0;
} }