0

In my understanding, fd0 is for stdin, so a process would just read from it and never write. Similarly fd1 and fd2 are for stdout/stderr, so a process would just write to it. But it seems like bash/zsh open a tty device file just once in read-write (u) mode and duplicate it across the 3 descriptors. Questions regarding this:

  1. Is the understanding right?
  2. Is the duplication just to save multiple entries in system file table (each in different mode: r/w)? Would there be a difference in behavior?
  3. Is it safe to assume that bash/zsh would open fd0/1/2 in read-write (u) mode independent of operating system?

1 Answer 1

2

Yes, that's the same file descriptor duplicated with dup2().

The main effect is indeed that they all refer to the same "open file" structure, so they share state like e.g. baud rate settings on serial consoles, or read/write position for files.

Your program can not assume anything about stdin/stdout/stderr beyond "they most likely exist". When stdout is redirected to a file or pipe, it is likely to be write-only, and refer to a different file than the others. Programs can generally assume that these file descriptors are open, and users know that weird things will happen if they force them closed.

If you absolutely need a terminal handle to talk to the user, open /dev/tty from your program, which gives you a handle to the controlling tty, if one exists. This can fail if your program is running as a background service.

2
  • POSIX requires that file descriptor 0 be open for reading, and 1 and 2 open for writing: “If a standard utility or a conforming application is executed with file descriptor 0 not open for reading or with file descriptor 1 or 2 not open for writing, the environment in which the utility or application is executed shall be deemed non-conforming, and consequently the utility or application might not behave as described in this standard.” Commented Jan 21, 2023 at 9:40
  • However the fact that the fds are open for reading and writing doesn’t mean that they are actually readable and writable; in particular, writing to fds 1 and 2 can fail with ENOSPC. Note too that /dev/tty can be “openable” but useless (e.g. from a graphical environment). Commented Jan 21, 2023 at 9:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .