C: dup and close-on-exec C: dup and close-on-exec unix unix

C: dup and close-on-exec


The advice is wrong. Close-on-exec is set only on file descriptors that your program has explicitly asked to be close-on-exec.

The reasons you may choose to use dup2 may be:

  • The process to be executed expects its I/O to be via particular file descriptors (usually 0, 1, and 2, corresponding to standard input, output and error streams respectively), or
  • the process will close some file descriptors, for whatever reason, and you need this fd to be outside the range to be closed.

The description is also slightly misleading - it's only the new descriptor (i.e. the return value from dup() or dup2()) which has close-on-exec unset. The close-on-exec state of the original fd is unchanged.