Does exec preserve file descriptors Does exec preserve file descriptors unix unix

Does exec preserve file descriptors


Yes. Open file descriptors are preserved across a call to exec. From the execve man page (all exec* calls are just a wrapper around this system call):

By default, file descriptors remain open across an execve(). File descriptors that are marked close-on-exec are closed; see the description of FD_CLOEXEC in fcntl(2).

  1. Yes, a file descriptor is the way that userspace refers to open files when making system calls. (Or socket, or pipe, etc.) The fact that they can be duplicated doesn't change that. They are simply multiple references to the same open file. See also:

  2. Yes, as mentioned in the man page quote.

In fact, many programs (including your shell) rely upon this feature. If it wasn't so, your program would start up without the standard in/out/error file descriptors open! When the shell runs a program, it forks, dup2's the open tty file descriptors to 0,1,2, and then execve's your new program.