Home > Back-end >  Standard streams vs. non-standard streams
Standard streams vs. non-standard streams

Time:09-21

The so-called "standard streams" in Linux are stdin, stdout, and stderr. But they must be called "standard" for a reason. Are there non-standard streams? And are these non-standard streams fundamentally treated differently by the kernel?

CodePudding user response:

In Unix ideology, everything should either be a file or a directory. This is why you can see your devices in /dev or your running processes in /proc. There are some exceptions depending on the implementation or distro. But everything you can "touch" or think as a "thing" is typically represented by a file

As JayC667 said a stream is just a sequence of bytes, which in the end is just a file. For example you can open a file (using fopen) and then use fprintf to write in the newly opened stream. There are many other examples of non-standard streams all typically contain a file handler, for standard ones, the file handler of stdin is 0, stdout 1, and stderr is 2; these don't change. Using write() you can use these ids to write to any stream although since only these three are standard you mostly won't be hardcoding any number in, other than these three (as usual there are some exceptions).

Another thing that might help you understand the concept is, if you are on linux you can do ps -ef | grep <program> and then go to /proc/<pid>/fd to see the opened file descriptors. Tipically you will find the first two standard file descriptors(stdin, and stdout) along with other "non standard" ones

CodePudding user response:

The standard streams are simply the ones ordinarily open when starting a new program in a new process.

Processes may open other streams, whether to regular files, devices (or pseudo-devices), network connections, or what have you. To the operating system kernel, other streams opened by a process are not fundamentally different from the standard streams.

When a shell executes a command, the shell is responsible for setting up the standard streams as it creates the new process and starts execution of the program. It does this through ordinary system calls to open or otherwise work with streams. If you write your own program to create a new process, it can configure the streams differently from standard, and the operating system will not care.

Linux is Unix-like, and The Single Unix Specification has an section “stderr, stdin, stdout - standard I/O streams” which says:

… At program start-up, three streams shall be predefined and need not be opened explicitly: standard input (for reading conventional input), standard output (for writing conventional output), and standard error (for writing diagnostic output)…

  • Related