next up previous
Next: 2.13 Normal and Abnormal Endings Up: 2. Environmentally Friendly I/O Previous: 2.11 Opening Streams Over File Descriptors

2.12 Passing File Descriptors

The normal inheritance of file descriptors by child processes suffices for many purposes, one of the most typical being when servers use child processes to deal with clients, as is illustrated by several examples in Section 3.2 [Concurrent Servers].

However, there are cases where it is convenient to be able to pass file descriptors to existing processes. For example, an httpd daemon will often optimize performance by maintaining a pool of child processes. Rather than spawning a new process for each new request, the daemon may pass the file descriptor created for the corresponding connection down to an existing process for handling. Passing file descriptors ``up'' a tree of processes can also be useful, such as when a child process is appointed to perform an open and related activities that might result in a crash. If the child process completes this extended open operation successfully, it can safely pass the new file descriptor up to the parent process, whereas if it crashes, no harm is done. (Isolating delicate operations in small processes to limit the damage they can do is a running theme of this dissertation--cf. Chapter 3 [Internet Sockets], and Sections 4.2.1 [Video Services], 4.2.2 [Camera Control Services], 5.3.2 [On Limits]-5.3.4 [On Clients], and 6.5 [Exceptions].)

In order for a file descriptor to be passed, the sender and receiver must already share a pipe or pump stream for its conveyance. Given a writable file descriptor pd1 for such an open stream, and a file descriptor fd1 to be passed, the sender executes *

send_fd (pd1fd1);
and makes a rendezvous with the receiver, which has a readable file descriptor pd2 for its end of the conveyance stream and executes *
fd2 := recv_fd pd2;
Note that the resulting fd2 is allocated in the receiver's process space, and may be numerically different from fd1, even though it refers to the same kernel structure. It is an alias, chosen automatically in the same way as by the low-level dup routine described in Section 2.17.1 [I/O and File Descriptors].

The mechanism underlying this generalized passing of file descriptors is defined in Unix 98, but at the time of this writing is not yet present in all versions of Unix in common use. In some versions an alternative mechanism exists, though in some of those it is only available to superuser processes. This situation will surely improve, but programs which use send_fd or recv_fd cannot currently be considered fully Unix-portable in practical terms. Solaris is among the operating systems in which full fd-passing support is already implemented, however.


next up previous
Next: 2.13 Normal and Abnormal Endings Up: 2. Environmentally Friendly I/O Previous: 2.11 Opening Streams Over File Descriptors
David Bacon
1999-12-10