Thursday, May 21, 2026

stdin , stdout and stderr

In computing, stdin, stdout, and stderr are the three standard data streams that connect a program to its environment (like a terminal or another program) as soon as it starts running.

They act like pipes that allow data to flow in and out of a process.

The Three Standard Streams

Name Stream Type File Descriptor Default Connection Purpose
stdin Standard Input 0 Keyboard Receiving input data or commands.
stdout Standard Output 1 Terminal Screen Displaying successful results of a command.
stderr Standard Error 2 Terminal Screen Displaying error messages or diagnostics.

Why Separate stdout and stderr?

Even though both usually print to your screen, they are separate channels. This separation allows you to:

  • Redirect output: Save a command's results to a file while still seeing error messages on your screen.
  • Filter errors: In automated pipelines (like Jenkins or GitHub Actions), tools can flag a task as failed only if data appears in the stderr stream.

Redirection Examples

You can use shell operators to change where these streams go:

# Redirect Output
ls > files.txt

# Redirect Errors
grep "text" file 2> errors.log

# Combine Streams
command > output.log 2>&1

# Redirect Input
mysql < database.sql
  • Redirect Output (> or 1>): Sends standard output to a file instead of the terminal.
  • Redirect Errors (2>): Saves only the error messages.
  • Combine Streams (2>&1): Sends both output and errors to the same place.
  • Redirect Input (<): Feeds a file into a program as input.

Standard Streams in Different Programming Languages

Most programming languages handle these streams in a very similar way:

Language Standard Input (stdin) Standard Output (stdout) Standard Error (stderr) Redirect Methods
C stdin stdout stderr freopen()
C++ std::cin std::cout std::cerr (unbuffered)
std::clog (buffered)
std::ios::rdbuf()
Python sys.stdin sys.stdout sys.stderr Overwriting sys.stdout or using contextlib.redirect_stdout
JavaScript (Node.js) process.stdin process.stdout process.stderr Shell redirection or wrapped write streams
Java System.in System.out System.err System.setIn(), System.setOut(), System.setErr()
C# Console.In
(Shortcut: Console.Read)
Console.Out
(Shortcut: Console.Write)
Console.Error Console.SetIn(), Console.SetOut(), Console.SetError()

Conclusion: stdin, stdout, and stderr are fundamental concepts in operating systems and programming. Understanding them is essential for shell scripting, automation, debugging, and building robust software systems.

No comments:

Post a Comment

kubernetes controllers and workloads

In Kubernetes, Workloads are the applications you run on the cluster, while Controllers are the background control loops that watch the st...