Are STDIN_FILENO and STDOUT_FILENO read only in c? Are STDIN_FILENO and STDOUT_FILENO read only in c? unix unix

Are STDIN_FILENO and STDOUT_FILENO read only in c?


The constants themselves (on POSIX, STDIN_FILENO is 0 and STDOUT_FILENO is 1) are indeed read-only, but the file descriptors they characterize may be closed and something else opened in their place; they're just ordinary file descriptors (usually with a flag set so that they stay open on an execve() system call).

The thing that is changing is the table of file descriptors for the process that resides inside the OS kernel. See that syscall instruction? That's really important here; that's the trap out of your process into the OS.


This is the final part of daemonizing and involves redirecting stdout and stdin to /dev/null because they are not going to be used later.

Daemons normally write to log files, not to the standard output.

Citing this article:

Once it is running a daemon should not read from or write to the terminal from which it was launched. The simplest and most effective way to ensure this is to close the file descriptors corresponding to stdin, stdout and stderr. These should then be reopened, either to /dev/null, or if preferred to some other location. There are two reasons for not leaving them closed:

  • to prevent code that refers to these file descriptors from failing, and
  • to prevent the descriptors from being reused for some other purpose.


Closing stdin and stdout works perfectly fine. Although when you do this you cannot read from them anymore and have to use the dup()'d descriptors.