Terminals - Old school stuff

Users browsing this thread: 1 Guest(s)
josuah
Long time nixers
Thanks for this episode, it brought clarifications when I was needing it.

Some example of tcgetattr and tcsetattr for putting the terminal in raw mode: https://github.com/antirez/kilo/blob/mas...#L203-L235

- It backup current terminal attributes with tcgetattr,

- copy it and set the required bitwise flags for setting the terminal in raw mode (with the bitwise OR: '|', bitwise not '~' and bitwise and '&'),

Code:
01001001  <- this changes something like this
00001000  <- to something like this
`-----`---- these two bytes got removed.

- apply the changes by passing it the modified structure to tcsetattr,

- while quitting, it sets the saved attributes back with tcsetattr.

I figured out that this was enough to get raw terminal:

Code:
enum { RAW, RESET }

int tty_fd;


[...]


/*
* Set terminal to raw mode or reset it back.
*
* RAW opens /dev/tty in a global tty_fd variable and RESET closes it
*/
void
set_terminal(int mode)
{
    extern int tty_fd;  /* you do not need this line if tty_fd is in this same file */

    struct termios termios_p;

    if (mode == RAW)
        tty_fd = open("/dev/tty", O_RDWR);

    if (tcgetattr(tty_fd, &termios_p)) {
        perror("tcgetattr");
        exit(EXIT_FAILURE);
    }

    if (mode == RAW) {
        termios_p.c_lflag &= ~(ICANON | ECHO | IGNBRK);
    } else if (mode == RESET) {
        termios_p.c_lflag |=  (ICANON | ECHO | IGNBRK);
    }

    if (tcsetattr(tty_fd, TCSANOW, &termios_p)) {
        perror("tcsetattr");
        exit(EXIT_FAILURE);
    }

    if (mode == RESET)
        tty_fd = close(tty_fd);
}

You can now call "set_terminal(RAW)" at startup of the program (like after argument parsing), and call "set_terminal(RESET)" before to quit.

Do not forget to also call "set_terminal(RESET)" if you program exits due to error.

I tested it a very few, you can use antirez's code if this does not work for you.


Messages In This Thread
Terminals - by venam - 23-04-2017, 05:39 AM
RE: Terminals - by venam - 23-04-2017, 05:59 AM
RE: Terminals - by robotchaos - 26-04-2017, 12:39 PM
RE: Terminals - by venam - 27-04-2017, 04:02 AM
RE: Terminals - by jkl - 27-04-2017, 08:00 AM
RE: Terminals - by mrtn - 11-05-2017, 03:49 AM
RE: Terminals - by josuah - 03-08-2017, 09:05 AM
RE: Terminals - by josuah - 03-08-2017, 09:24 AM
RE: Terminals - by resk - 27-10-2017, 04:49 AM
RE: Terminals - by venam - 27-10-2017, 10:52 AM