Standard streams (0, 1, 2)
What you'll learn: How to identify the three default communication channels every C program uses to talk to the outside world.
The Three Open Doors
When you launch a C program, the operating system doesn’t just run your code; it hands the program three open "communication channels" called File Descriptors.
Think of a file descriptor like a numbered plug on a switchboard. By default, every program has three plugs ready to go, numbered 0, 1, and 2. You don’t have to open them; they are already waiting for you the moment main() starts.
0: Standard Input (stdin)
This is the "ear" of your program. It is the channel through which your program receives data. By default, this is connected to your keyboard. When you use scanf() or getchar(), the program is listening to File Descriptor 0.
1: Standard Output (stdout)
This is the "mouth" of your program. It is the primary channel for sending data out. By default, this is connected to your terminal screen. When you use printf(), you are writing data to File Descriptor 1.
2: Standard Error (stderr)
This is the "emergency megaphone." It is a separate channel specifically for error messages or diagnostic alerts. While it also points to your terminal screen by default, it is kept separate from stdout so that you can record your program’s actual results to a file while still seeing error messages pop up on the screen.
Seeing the Numbers in Action
In C, these streams are represented by the constants STDIN_FILENO, STDOUT_FILENO, and STDERR_FILENO. These are just fancy names for the integers 0, 1, and 2.
#include <unistd.h>
#include <string.h>
int main() {
char *msg = "Hello, Standard Output!\n";
char *err = "Something went wrong on Standard Error.\n";
// write(file_descriptor, buffer, length)
// 1 is stdout
write(1, msg, strlen(msg));
// 2 is stderr
write(2, err, strlen(err));
return 0;
}
Why separate them?
By using separate numbers, the operating system allows you to redirect them. You can tell the computer: "Take everything from channel 1 (the results) and save it to a file, but keep channel 2 (the errors) showing on my screen so I know if something breaks."
Key takeaway
Every C program starts with three default file descriptors: 0 (Input), 1 (Output), and 2 (Error).