0

According to this answer, stdin, stdout, and stderr are all initially connected to the same place (same as /dev/tty), and the convention of reading from stdin and writing to stdout and stderr is only that: a convention.

In that case, why have separate stdin and stdout streams, rather than combining them into a single one?

Draconis
  • 666

2 Answers2

1

Having an input stream separate from an output stream makes it easier for a program to to write its output at the same time as it's reading its input.

It makes it easier to allow a program to write its output elsewhere than to whence its input came from, using redirections or pipes.

Also, other than being just a convention, the three standard I/O streams are also standard. See e.g. the section on Standard I/O Streams in the System Interfaces part of the POSIX standard.

The Rationale for that section says:

Although the ISO C standard guarantees that, at program start-up, stdin is open for reading and stdout and stderr are open for writing, this guarantee is contingent (as are all guarantees made by the ISO C and POSIX standards) on the program being executed in a conforming environment. Programs executed with file descriptor 0 not open for reading or with file descriptor 1 or 2 not open for writing are executed in a non-conforming environment. Application writers are warned [...] not to execute a standard utility or a conforming application with file descriptor 0 not open for reading or with file descriptor 1 or 2 not open for writing.

Kusalananda
  • 333,661
1

A FILE pointer such as stdin, stdout and stderr can only contain one underlying file descriptor. Thus if you have a pipeline setup like:

ls | grep foo | less

Then grep's stdin, stdout and stderr all have different fileno()s because there are two connected pipe()s. Thus there must be different FILEs also.

ctrl-d
  • 952
  • 1
    This is also the reason that standard error was invented in the first place. Until 7th Edition, errors were passed down pipelines. – JdeBP Jul 01 '18 at 15:59