File Descriptor Passing¶
File descriptor passing allows one process to send an already-open file descriptor to another process through a UNIX domain socket.
This is useful because the receiving process does not need to know how the file descriptor was created. It only receives a valid descriptor that refers to the same underlying kernel object.
What Problem It Solves¶
Use file descriptor passing when one process should create or own a resource, but another process should operate on it.
Typical use cases:
- privilege separation
- supervisor/worker architectures
- passing
eventfd, socket, or device descriptors - sharing access to kernel objects without reopening them
Core Concepts¶
| Concept | Description |
|---|---|
sendmsg() |
Sends data and ancillary control messages |
recvmsg() |
Receives data and ancillary control messages |
SCM_RIGHTS |
Control message type used for file descriptor passing |
struct cmsghdr |
Header for ancillary data |
CMSG_SPACE() |
Computes buffer size for control data |
CMSG_LEN() |
Computes payload length for control data |
Key Rule¶
The file descriptor number may be different in the receiving process, but it refers to the same underlying open file description or kernel object.
Common Pitfalls¶
Warning
Always close file descriptors that are no longer needed in both sender and receiver processes. Descriptor passing can easily cause resource leaks.
Note
SCM_RIGHTS requires a UNIX domain socket. It is not a generic TCP/IP socket feature.