I understand that stdin and stdout (at least in UNIX parlance) are stream buffers, and that stdout is used to output from a program to the console (or to then be piped by a shell, etc), and that stdin is for standard input to a program..
So why is it, at least on macOS, that they can be used interchangeably (stdout as stdin, and vice versa?
Examples:
If you run
cat /dev/stdinthen type something in, and it echoes it back. Running the command ascat /dev/stdoutdoes the same thing.Similarly,
echo "Hey There" > /dev/stdoutandecho "Hey There" > /dev/stdinboth 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, typing a single word, followed by EOF (Ctrl+D) works as expected.
/dev/stdinand/dev/stdoutare interchangeable does not imply thatstdinandstdoutare interchangeable. In particular, if you start a process with> /dev/stdinthen it will not be possible to read from the process's standard output stream. - Brian Bistd::fstreamopens in read/write mode by default. If you do> fooon the terminal, it will openfooin write-only mode and the file descriptor will not be usable for reading. - Brian Bi