Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 17.4 Passing File Descriptors 643


process table entry

...


fd 0:
fd 1:
fd 2:
fd 3:

flagsfd pointerfile

process table entry

...


fd 0:
fd 1:
fd 2:
fd 3:
fd 4:

flagsfd pointerfile

file status flags
current file offset
v-node pointer

file table

v-node information
v_data

i-node information
current file size
i_vnode

v-node table

Figure 17.11 Passing an open file from the top process to the bottom process

Aprocess (normally a server) that wants to pass a descriptor to another process
calls eithersend_fdorsend_err.The process waiting to receive the descriptor (the
client) callsrecv_fd.
The send_fdfunction sends the descriptor fd_to_send across using the UNIX
domain socket represented byfd.Thesend_errfunction sends theerrmsgusingfd,
followed by thestatusbyte. The value ofstatusmust be in the range−1through−255.
Clients call recv_fd to receive a descriptor.Ifall is OK (the sender called
send_fd), the non-negative descriptor is returned as the value of the function.
Otherwise, the value returned is thestatusthat was sent bysend_err(anegative value
in the range−1through− 255 ).Additionally, if an error message was sent by the server,
the client’suserfuncis called to process the message. The first argument touserfuncis
the constant STDERR_FILENO,followed by a pointer to the error message and its
length. Thereturn value fromuserfuncis the number of bytes written or a negative
number on error.Often, the client specifies the normalwritefunction as theuserfunc.
We implement our own protocol that is used by these three functions. To send a
descriptor,send_fdsends two bytes of 0, followed by the actual descriptor.Tosend an
error,send_errsends theerrmsg,followed by a byte of 0, followed by the absolute
value of thestatusbyte(1through 255).Therecv_fdfunction reads everything on the
Free download pdf