~/blog/terminal/01-what-exactly-is-a-terminal.md
What exactly is a terminal?
Most developers use a terminal every day. We use it to write code, manage files, run applications, and interact with our operating systems. But have you ever wondered how does a terminal display colors? How does it move the cursor, capture keyboard input, or detect mouse events? How do applications like Vim, htop, and other terminal-based applications render complex interfaces without a traditional graphical window?.
Throughout the development of libterm, I learned many interesting things about how terminals work, how applications communicate with them, and how we can build interactive user interfaces using relatively simple low-level mechanisms.
In this article series, I want to share what I have learned. We will start with the fundamentals, explore the history and architecture of terminals, understand escape sequences, manipulate the terminal screen, handle keyboard and mouse input, and eventually build our own terminal UI library from scratch.
What exactly is a terminal?
A computer terminal is an electronic or electromechanical hardware device that can be used for entering data into, and transcribing data from, a computer or a computing system. wikipedia
Let me make it easier for you to understand. On Unix and Unix-like operating systems (e.g., Linux and macOS), a terminal is essentially exposed as a file. You can type tty in your terminal, and you will see a path printed, such as /dev/pts/3. That path represents your terminal.
Your terminal emulator communicates with this terminal through a pair of connected devices called a pseudoterminal (PTY). It reads output, interprets escape sequences, and renders the result into a human-readable interface. It also takes your input, such as keyboard presses, and sends it back as bytes that applications can understand.
On Windows, the idea is similar. There is a special device name, CON, which stands for console. Try running echo hello > CON in CMD, and the text will appear right back in your window, as if you were writing to a file.
Reading input is where Windows differs. Instead of dealing with raw bytes, the native Windows Console API can provide structured events, such as “Up arrow pressed while holding Shift” or “Window resized.” You don’t have to manually parse escape sequences to understand these events.
Terminal, Terminal emulator and Shell
Before we go any further, we need to understand the difference between a terminal, a terminal emulator, and a shell. These three terms are often used interchangeably, but they are actually different things with different responsibilities.
Terminal
Originally, a terminal was a physical device consisting of a keyboard and a display that allowed users to communicate with a computer. The terminal itself was primarily responsible for sending input and displaying output, while the actual computation happened on the connected computer.
Today, we no longer need dedicated physical terminals. Modern operating systems provide software-based mechanisms that serve a similar purpose, on Unix-like systems, a terminal provides a communication interface between an application and a user. As we saw earlier, this interface can be accessed through a device file such as /dev/pts/3.
Terminal Emulator
A terminal emulator is a software application that emulates the behavior of a physical terminal, if you are using Kitty, Alacritty, Ghostty, GNOME Terminal, or Windows Terminal, you are using a terminal emulator.
A terminal emulator is responsible for displaying text, interpreting escape sequences, rendering colors, managing cursor positions, and forwarding keyboard and mouse input to applications, for example, when an application sends an escape sequence to change the text color to red, the terminal emulator interprets that sequence and renders the following text in red, the application does not need to know how to draw text on your monitor. It simply communicates with the terminal using an agreed-upon protocol, this is an important concept that we will use extensively when building our own terminal UI library.
Shell
A shell is a program that provides an interface for interacting with the operating system, Bash, Zsh, Fish, and PowerShell are examples of shells.
When you type a command such as ls, your terminal emulator forwards your input through the terminal interface. The shell receives that input, interprets the command, executes the appropriate program, and the resulting output is sent back to the terminal, the terminal emulator then renders that output on your screen.
One important thing to understand is that a terminal emulator does not execute shell commands itself. That is the responsibility of the shell, a shell is also not a requirement for a terminal application. A terminal emulator can launch an application such as Vim or htop directly without running an interactive shell.
How do they work together?
To simplify things, think of the terminal emulator as the presentation layer, the terminal as the communication interface, and the shell as an application that interprets your commands, when we build a terminal UI application, we are essentially building another kind of application that communicates with the terminal, instead of creating a graphical window, drawing pixels, or using a graphical UI framework, we send characters and control sequences to the terminal and let the terminal emulator handle the rendering.
But how exactly does this communication happen? How can a simple stream of bytes represent colors, cursor movements, and even an entire user interface? to understand that, we first need to understand TTY and PTY.
Understanding TTY and PTY
If you have spent some time working with Linux, you have probably encountered the term TTY. But what exactly does it mean, and why is it important for terminal programming?
What is TTY?
TTY stands for Teletypewriter, a name that comes from the early days of computing, when users interacted with computers through physical electromechanical devices, unlike modern terminals, early teletypewriters did not have a screen. They had a keyboard for entering data and a printer for displaying the output on paper, although technology has evolved significantly since then, Unix has preserved the concept of TTY as an abstraction for terminal communication.
In modern Unix-like operating systems, a TTY is a terminal device managed by the operating system kernel. It provides an interface through which applications can receive input and send output.
On Linux, you can find terminal devices under the /dev directory, such as:
/dev/tty
/dev/tty1
/dev/tty2
/dev/tty3
On most Linux desktop systems, you can switch to a virtual console by pressing Ctrl + Alt + F3. You can interact with the operating system without using a graphical terminal emulator, this is an example of a virtual terminal provided directly by the Linux kernel.
What is PTY?
PTY stands for Pseudoterminal. As the name suggests, it is a software-based mechanism that emulates the behavior of a terminal device, when you open a terminal emulator such as Kitty, Alacritty or Ghostty, you are typically interacting with a pseudoterminal.
Try running the following command:
tty
You might see something like this:
/dev/pts/3
This is the slave side of a pseudoterminal. Unlike a traditional hardware terminal or a Linux virtual console, a pseudoterminal allows two programs to communicate with each other through a terminal-like interface.
A pseudoterminal consists of two connected endpoints:
- PTY Master: Typically controlled by the terminal emulator.
- PTY Slave: Typically used by the shell or terminal application.
Both endpoints are managed by the operating system kernel.
How does a PTY work?
When you press a key on your keyboard, your terminal emulator converts that input into bytes and writes them to the PTY master, the kernel processes those bytes according to the terminal’s current configuration and makes the input available through the PTY slave, where the shell or terminal application can read it.
When an application wants to display something, it writes bytes to the PTY slave. Those bytes become available through the PTY master, where the terminal emulator reads, interprets, and renders them on your screen, this communication happens in both directions, the interesting part is that the application does not need to know which terminal emulator you are using. Whether you are using Kitty, Alacritty, or Ghostty, the application communicates through the same operating system abstraction.
Talking directly to a PTY
Let’s try a simple experiment, open two terminal windows. In the first terminal, run:
tty
Assume the output is:
/dev/pts/3
Now, in the second terminal, run:
echo "Hello from another terminal!" > /dev/pts/3
You should see the message appear in your first terminal, assuming you have permission to write to that device, notice that we did not send a command to the shell in the first terminal. Instead, we wrote directly to its terminal device, and the terminal emulator displayed the output.
This demonstrates one of the fundamental concepts of terminal programming: we can communicate with a terminal by writing bytes to its device.
Common terminal devices
On Linux, there are several terminal-related devices worth knowing:
| Device | Description |
|---|---|
/dev/tty |
The controlling terminal of the current process. |
/dev/tty1 |
A Linux virtual console. |
/dev/pts/3 |
An individual PTY slave device. |
/dev/ptmx |
A device used to allocate a new pseudoterminal master and its associated slave. |
Why does this matter for terminal UI programming?
When we build our own terminal UI library, we do not need to implement a terminal emulator or create a pseudoterminal ourselves, instead, we can use the existing terminal interface provided by the operating system to receive input, display text, change colors, move the cursor, and eventually render an entire user interface.
However, before we can do that, we need to understand how an application reads and writes data through this interface, this brings us to our next topic: Standard Input, Output, and Error.
Understanding Standard Input, Output, and Error
Now that we understand how terminals and pseudoterminals work, let’s explore how an application actually communicates with them.
When you run a program, it typically has three standard communication streams available: standard input (stdin), standard output (stdout), and standard error (stderr), these streams provide a standard way for applications to receive input and produce output without needing to know exactly where the data comes from or where it goes.
Understanding File Descriptors
On Unix-like operating systems, a file descriptor is a non-negative integer that represents an open file or another I/O resource managed by the operating system.
Despite its name, a file descriptor is not limited to regular files. It can also represent a terminal device, a pipe, or even a network socket.
By convention, a process starts with three standard file descriptors:
| File Descriptor | Name | Purpose |
|---|---|---|
| 0 | stdin | Receiving input |
| 1 | stdout | Writing normal output |
| 2 | stderr | Writing errors and diagnostics |
In C, POSIX provides constants for these file descriptors through the <unistd.h> header:
STDIN_FILENO // 0
STDOUT_FILENO // 1
STDERR_FILENO // 2
When you launch an application from your terminal, these file descriptors are typically connected to the slave side of your pseudoterminal, however, they are not necessarily connected to a terminal. They can also be redirected to files, pipes, or other resources.
Writing to the Terminal
If you have written a C program before, you are probably familiar with printf().
#include <stdio.h>
int main(void) {
printf("Hello, terminal!\n");
return 0;
}
But we can also achieve the same result using the POSIX write() function.
#include <unistd.h>
int main(void) {
const char message[] = "Hello, terminal!\n";
write(STDOUT_FILENO, message, sizeof(message) - 1);
return 0;
}
Both programs produce the same visible output, but they operate at different levels of abstraction, printf() is a C standard library function that provides formatting and buffering. On the other hand, write() is a lower-level POSIX interface that writes bytes to a file descriptor without C standard I/O buffering, for terminal UI programming, having direct control over the bytes we send and when we send them is particularly useful.
Later, we will use this mechanism to change colors, move the cursor, clear the screen, and render our own user interface.
Reading from the Terminal
Just as we can write bytes to a terminal, we can also read bytes from it.
#include <unistd.h>
int main(void) {
char buffer[128];
ssize_t n = read(STDIN_FILENO, buffer, sizeof(buffer));
if (n > 0) {
write(STDOUT_FILENO, buffer, n);
}
return 0;
}
This simple program reads input from standard input and writes it back to standard output.
Try running it and typing something. You will probably notice that the program waits until you press Enter before it receives your input, why does this happen? Why can applications like Vim respond immediately when you press a key, while our application cannot?, this behavior is controlled by the terminal’s line discipline and its configuration. We will explore this in a later section when we discuss canonical mode and raw mode.
Standard Streams Are Not Always Connected to a Terminal
One of the interesting things about standard streams is that applications can use them without knowing what they are connected to.
Consider the following command:
echo "Hello, world!" > output.txt
Instead of displaying the output in your terminal, the shell redirects standard output to a file.
Now consider another example:
echo "Hello, world!" | cat
In this case, the standard output of echo is connected through a pipe to the standard input of cat.
Neither application needs to know how the other application works. They simply read and write data through their standard streams, this flexibility is one of the fundamental design principles of Unix.
Is Our Application Running Inside a Terminal?
Since standard streams are not always connected to a terminal, how can our application determine whether it is actually communicating with one?, POSIX provides a function called isatty().
#include <stdio.h>
#include <unistd.h>
int main(void) {
if (isatty(STDOUT_FILENO)) {
printf("Standard output is a terminal.\n");
} else {
printf("Standard output is not a terminal.\n");
}
return 0;
}
This function will become useful when building our terminal UI library. We generally do not want to send terminal-specific control sequences to a regular file or an incompatible output destination.
Why does this matter?
At this point, we have learned that an application can communicate with a terminal simply by reading and writing bytes through file descriptors.
We do not need a graphical rendering API, a window manager, or even direct access to the display hardware, but if all we are doing is writing bytes, how can we tell the terminal to change colors, move the cursor, or clear the screen?, the answer lies in how the terminal interprets those bytes.
This brings us to our next topic: The Terminal Is a Stream of Bytes.
The Terminal Is a Stream of Bytes
In the previous section, we learned that applications can communicate with a terminal by reading and writing bytes. But how can a simple stream of bytes represent text, colors, cursor movements, and even an entire user interface?
The answer is that not every byte sent to a terminal is intended to be displayed as a character. Some bytes represent text, while others represent instructions that the terminal interprets.
Before we explore these instructions, we need to understand how characters are represented in a computer.
Understanding ASCII
ASCII stands for American Standard Code for Information Interchange. It is a character encoding standard that represents 128 different characters using 7 bits.
Every ASCII character has a corresponding numerical value. For example:
| Character | Decimal | Hexadecimal | Binary |
|---|---|---|---|
| A | 65 | 0x41 | 01000001 |
| B | 66 | 0x42 | 01000010 |
| a | 97 | 0x61 | 01100001 |
| 0 | 48 | 0x30 | 00110000 |
| Space | 32 | 0x20 | 00100000 |
When we write the following code in C:
write(STDOUT_FILENO, "Hello", 5);
We are essentially sending the following bytes to the terminal:
0x48 0x65 0x6C 0x6C 0x6F
The terminal emulator interprets these bytes as characters and displays Hello on the screen.
We can even write those bytes directly:
#include <unistd.h>
int main(void) {
const char bytes[] = {
0x48, 0x65, 0x6C, 0x6C, 0x6F
};
write(STDOUT_FILENO, bytes, sizeof(bytes));
return 0;
}
Both examples produce the same output. From the terminal’s perspective, there is no difference between them.
Printable Characters and Control Characters
Not all ASCII characters represent something that can be displayed on a screen, ASCII contains 95 printable characters and 33 control characters. Control characters were originally designed to control communication equipment such as teletypewriters.
Many of these characters are still relevant in modern terminal programming.
| Name | Decimal | Hexadecimal | C Representation |
|---|---|---|---|
| Null (NUL) | 0 | 0x00 | \0 |
| Bell (BEL) | 7 | 0x07 | \a |
| Backspace (BS) | 8 | 0x08 | \b |
| Horizontal Tab (HT) | 9 | 0x09 | \t |
| Line Feed (LF) | 10 | 0x0A | \n |
| Carriage Return (CR) | 13 | 0x0D | \r |
| Escape (ESC) | 27 | 0x1B | \x1b |
| Delete (DEL) | 127 | 0x7F | \x7f |
Unlike printable characters, control characters can instruct the terminal to perform certain actions, for example, a carriage return moves the cursor back to the beginning of the current line.
Let’s try it ourselves:
#include <unistd.h>
int main(void) {
write(STDOUT_FILENO, "Hello", 5);
write(STDOUT_FILENO, "\r", 1);
write(STDOUT_FILENO, "World", 5);
return 0;
}
You might expect the terminal to display HelloWorld, but instead, it displays:
World
This happens because \r moves the cursor back to the beginning of the line, allowing World to overwrite Hello.
We have just manipulated the terminal screen without using any graphical API or external library.
Beyond ASCII: Understanding UTF-8
ASCII is sufficient for representing basic English characters, but what about Arabic, Japanese, Chinese, or emojis? modern terminals commonly use UTF-8, a variable-length character encoding capable of representing Unicode characters, unlike ASCII, a Unicode character encoded in UTF-8 can occupy between one and four bytes.
| Character | Unicode | UTF-8 Bytes | Byte Count |
|---|---|---|---|
| A | U+0041 | 41 |
1 |
| é | U+00E9 | C3 A9 |
2 |
| 中 | U+4E2D | E4 B8 AD |
3 |
| 🚀 | U+1F680 | F0 9F 9A 80 |
4 |
This means that the number of bytes in a string does not necessarily represent the number of characters, and the number of characters does not necessarily represent how many cells they occupy on the terminal screen.
For example:
#include <stdio.h>
#include <string.h>
int main(void) {
printf("%zu\n", strlen("🚀"));
return 0;
}
Assuming the string is encoded in UTF-8, the output is:
4
Even though we see a single emoji, it occupies four bytes in memory and typically two character cells on the terminal screen, this distinction will become particularly important when we build our terminal rendering engine. We cannot simply use the length of a string to determine how much space it occupies on the screen.
We will explore Unicode and character width in greater detail later in this series.
The Escape Character
Among all ASCII control characters, there is one that is particularly important for terminal programming: the Escape character, it has a decimal value of 27, or 0x1B in hexadecimal.
In C, we can represent it as:
"\x1b"
The Escape character is commonly used to introduce a sequence of bytes that the terminal interprets as an instruction.
For example:
#include <unistd.h>
int main(void) {
const char message[] = "\x1b[31mHello\x1b[0m\n";
write(STDOUT_FILENO, message, sizeof(message) - 1);
return 0;
}
If you run this program in a compatible terminal emulator, you will see the word Hello displayed in red, notice that we did not call a function to change the text color. We simply sent a specific sequence of bytes to the terminal, and the terminal emulator interpreted those bytes as instructions. this is the foundation of modern terminal UI programming.
The Terminal as a Communication Protocol
At this point, we can start thinking about the terminal as more than just a place to display text, it is an environment that understands a communication protocol. Our application sends bytes, and the terminal interprets those bytes according to a set of rules, by understanding these rules, we can change colors, move the cursor, clear parts of the screen, and eventually build complex interactive user interfaces, the terminal emulator handles the actual rendering. Our responsibility is to send the correct instructions.
So, what are these instructions, how are they structured, and what can we do with them? see you on the next part from this series.
Thanks for reading. If you found this useful, share it with someone who is curious about how terminals work. Questions, corrections or feedback are always welcome: reach me by email, on GitHub or on LinkedIn.