Raw mode
- C course
- Advanced
- Lesson 44/83
- 5 min
Learn to put the terminal in raw mode.
What is raw mode?
Raw mode turns off the terminal's line mode and other processing; each keystroke reaches the program immediately. The cfmakeraw(&t) helper function brings the struct termios struct into raw mode; it clears ICANON, ECHO and many other flags.
It can also be done manually: t.c_lflag &= ~(ICANON | ECHO);. Before switching to raw mode, save the old settings with tcgetattr and restore them on exit with tcsetattr. For testing, printf("raw: 1\n") after cfmakeraw gives a deterministic output.
The cfmakeraw pattern
The typical flow: struct termios t;, read with tcgetattr(STDIN_FILENO, &t);, switch to raw with cfmakeraw(&t);, apply with tcsetattr(STDIN_FILENO, TCSANOW, &t);. On exit, restore the old settings.
For testing, the goal is to show the cfmakeraw call. tcsetattr may fail without a real terminal; but printf("raw: 1\n") still runs and is deterministic. In real apps, a function that restores the old settings is registered with atexit; so the terminal returns to normal mode when the program exits.
Practice Switch to raw mode
Declare struct termios t;. Read with tcgetattr(STDIN_FILENO, &t);. Switch to raw mode with cfmakeraw(&t);. Print the state with printf("raw: 1\n");.
Starter code
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
// Declare terminal struct and read
// Switch to raw mode
// Print state
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
int main(void) {
struct termios t;
tcgetattr(STDIN_FILENO, &t);
cfmakeraw(&t);
printf("raw: 1\n");
return 0;
}Expected output
raw: 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match raw mode parts
| Term | Meaning |
|---|---|
cfmakeraw |
Sets raw mode |
ICANON |
Line mode |
ECHO |
Echo back |
c_lflag |
Local mode |
2 Which flag is cleared in raw mode?
- O_NONBLOCK
- F_SETLK
- STDIN_FILENO
- ICANON Correct answer
Explanation: ICANON, the line mode flag, is cleared; each key arrives instantly.
3 cfmakeraw call
cfmakeraw(&____);
cfmakeraw(&t);
Explanation: cfmakeraw brings the t struct into raw mode.