raw mode implementation
This commit is contained in:
@@ -0,0 +1,10 @@
|
||||
##
|
||||
# TEST
|
||||
#
|
||||
# @file
|
||||
# @version 0.1
|
||||
|
||||
main: main.c
|
||||
$(CC) main.c -o main -Wall -Wextra -pedantic
|
||||
|
||||
# end
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
#include <ctype.h>
|
||||
#include <errno.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <termios.h>
|
||||
#include <unistd.h>
|
||||
|
||||
/* defines */
|
||||
#define CTRL_KEY(k) ((k) & 0x1f)
|
||||
|
||||
/* data */
|
||||
struct termios orig_termios;
|
||||
|
||||
/* terminal */
|
||||
|
||||
void die(const char *s) {
|
||||
perror(s);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
void disableRawMode() {
|
||||
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &orig_termios) == -1) {
|
||||
die("tcsetattr");
|
||||
}
|
||||
}
|
||||
|
||||
void enableRawMode() {
|
||||
if (tcgetattr(STDIN_FILENO, &orig_termios) == -1) {
|
||||
die("tcgetattr");
|
||||
}
|
||||
atexit(disableRawMode);
|
||||
|
||||
struct termios raw = orig_termios;
|
||||
raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
|
||||
raw.c_oflag &= ~(OPOST);
|
||||
raw.c_cflag |= (CS8);
|
||||
raw.c_lflag &= ~(ECHO | ICANON | ISIG | IEXTEN);
|
||||
raw.c_cc[VMIN] = 0;
|
||||
raw.c_cc[VTIME] = 1;
|
||||
|
||||
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1) {
|
||||
die("tcgetattr");
|
||||
}
|
||||
}
|
||||
|
||||
/* init */
|
||||
|
||||
int main() {
|
||||
char c;
|
||||
|
||||
enableRawMode();
|
||||
|
||||
while (1) {
|
||||
c = '\0';
|
||||
if (read(STDIN_FILENO, &c, 1) == -1 && errno != EAGAIN) {
|
||||
die("read");
|
||||
}
|
||||
if (iscntrl(c)) {
|
||||
printf("%d\r\n", c);
|
||||
} else {
|
||||
printf("%d ('%c')\r\n", c, c);
|
||||
}
|
||||
if (c == CTRL_KEY('q')) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user