Why do stdin and stdout seem interchangeable?

I understand that stdin and stdout (at least in UNIX language) are stream buffers, and this stdout is used to output from the program to the console (or for subsequent transfer through the shell, etc.), and stdin is for standard input into the program.

So why, at least on macOS, can they be used interchangeably (stdout as stdin and vice versa?

Examples:

  • If you run cat /dev/stdin , enter something and it will repeat it. Running a command like cat /dev/stdout does the same.

  • Similarly, echo "Hey There" > /dev/stdout and echo "Hey There" > /dev/stdin output "Hey There" back to the terminal.

  • It also works in C ++:

Example:

 #include <iostream> #include <string> #include <fstream> int main(int argc, const char * argv[]) { std::string echoString; std::fstream stdoutFile; stdoutFile.open("/dev/stdout"); stdoutFile << "Hey look! I'm using stdout properly!\nNow You trying using it wrongly: " << std::endl; stdoutFile >> echoString; stdoutFile << "You Typed: " << echoString << std::endl; } 

When prompted, enter one word, followed by EOF (Ctrl + D), as expected.

+7
c ++ unix shell stdout macos
source share
2 answers

Since, as a rule, when a program is called from an interactive terminal, without redirection, both standard input and standard output are connected to the same terminal device, for example /dev/tty (the actual device name changes depending on the current system).

The terminal device is a reader / writer. Reading from a terminal device reads the terminal output. Writing to a terminal device generates output on the terminal.

You still have discrete file descriptors, 0 and 1, but they are connected to the same device.

Think of it as a single bidirectional channel, which is dup ed for both file descriptors 0 and 1.

Linux behaves the same way (you can echo Foo >/dev/stdin and see the output):

 $ ls -al /proc/self/fd/[01] lrwx------. 1 mrsam mrsam 64 Nov 22 21:34 /proc/self/fd/0 -> /dev/pts/1 lrwx------. 1 mrsam mrsam 64 Nov 22 21:34 /proc/self/fd/1 -> /dev/pts/1 

So, for this process, file descriptors 0 and 1 are connected to /dev/pts/1 , the same pseudo-terminal device. Regardless of whether you read from file descriptor 0 or file descriptor 1, you end up reading from the same base device /dev , so it doesn't matter what actual file descriptor you use.

This, of course, depends on the operating system. Other POSIX-based operating systems can implement their standard input and output in other ways when you cannot write to standard input and read from standard output.

+3
source share

As you said, they are just stream buffers. There is nothing in them that would provide a specific usage pattern - just an agreement. The stdin, stdout, and stderr stream buffers are provided as a programming convenience.

0
source share

All Articles