CodeBlanks Logo Icon CodeBlanks

termios

Learn terminal configuration with termios.

What is termios?

termios is the POSIX terminal settings structure. struct termios is declared in <termios.h>; it holds the terminal's input processing, output processing and local mode settings. You read the current settings with tcgetattr(fd, &t) and apply new ones with tcsetattr(fd, TCSANOW, &t).

Important fields: c_lflag for local mode (e.g. ICANON enables line mode), c_oflag for output mode, c_iflag for input mode. STDIN_FILENO is usually the terminal descriptor. If the descriptor is not a terminal, tcgetattr returns -1; so for tests, a static printout is safe.

Reading with tcgetattr

tcgetattr(STDIN_FILENO, &t) copies the current terminal settings into struct termios t. You must call it before making changes; otherwise you lose the original settings.

For testing, you can print printf("termios read\n") after the call. If STDIN_FILENO is not a terminal (e.g. in a test environment), tcgetattr fails; but printf still runs. So the output is deterministic. In real apps, you check whether it is a terminal with isatty(STDIN_FILENO) and behave accordingly.

Practice Read terminal settings

Declare struct termios t;. Read the settings with tcgetattr(STDIN_FILENO, &t);. Print the state with printf("termios read\n");.

Starter code

main.c
#include <stdio.h>
#include <termios.h>
#include <unistd.h>

// Declare terminal struct
// Read settings
// Print read

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>
#include <termios.h>
#include <unistd.h>

int main(void) {
    struct termios t;
    tcgetattr(STDIN_FILENO, &t);
    printf("termios read\n");
    return 0;
}

Expected output

termios read

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which header declares the termios struct?

  • stdlib.h
  • stdio.h
  • termios.h Correct answer
  • math.h

Explanation: struct termios is declared in termios.h.

2 tcgetattr call

Question
tcgetattr(STDIN_FILENO, &____);
Answer
tcgetattr(STDIN_FILENO, &t);

Explanation: tcgetattr takes the address of t and fills the settings.

3 Match termios parts

Term Meaning
tcgetattr Reads settings
tcsetattr Applies settings
c_lflag Local mode
ICANON Line mode

All lessons in Advanced