I wrote th following code, to set the terminal to the non-canonical mode:
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
static struct termios old_terminal = {0};
static bool is_set = false;
static void restore_terminal(void) {
tcsetattr(STDIN_FILENO, TCSANOW, &old_terminal);
}
static inline void configure_terminal(void) {
if (!is_set) {
tcgetattr(STDIN_FILENO, &old_terminal);
struct termios new_terminal = old_terminal;
new_terminal.c_lflag &= ~ICANON; // Disable canonical mode
new_terminal.c_lflag &= ~ECHO; // Disable echo
tcsetattr(STDIN_FILENO, TCSANOW, &new_terminal);
atexit(restore_terminal); // Even if the application crashes, the terminal must be restored
is_set = true;
}
}
I use the auxiliary variable is_set
to garantee that if the user calls the function configure_terminal
twice, it doesn't screw the terminal.
My question is: Is there a way to remove variable is_set
? For instante, checking if the variable old_terminal was set already?
Thanks!