Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does exec preserve file descriptors

Tags:

This is actually a two-step question:

  1. What exactly is a file descriptor? I thought it was the most fundamental way to represent an open file. But since dup2 can make two different file descriptors point to the same file, then what is it that represents a unique file?

  2. If I do dup2 before exec, the whole program is then wiped out, does it still have the same file descriptor table? Do the redirected file descriptors still are redirected?

like image 284
Xufeng Avatar asked Mar 07 '14 03:03

Xufeng


People also ask

Does fork close file descriptors?

If another thread calls fork() in between the first and the second line, which is of course possible, the flag has not yet been set yet and thus this file descriptor won't get closed. So the only way that is really safe is to explicitly close them and this is not as easy as it may seem!

Does child process inherit file descriptors?

* The child inherits copies of the parent's set of open file descriptors. Each file descriptor in the child refers to the same open file description (see open(2)) as the corresponding file descriptor in the parent.

Does fork copy the file descriptor table?

The fork subroutine creates an identical copy of the entire file descriptor table for a child process. Contains entries for each open file.

Where are the file descriptors stored?

File descriptors are an index into a file-descriptor table stored by the kernel. The kernel creates a file-descriptor in response to an open call and associates the file-descriptor with some abstraction of an underlying file-like object; be that an actual hardware device, or a file-system or something else entirely.


1 Answers

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:

    • Can I check if two FILE* or file descriptor numbers refer to the same file?
    • two file descriptors to same file
  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.

like image 180
Jonathon Reinhart Avatar answered Oct 27 '22 02:10

Jonathon Reinhart