sthustfo sthustfo - 9 months ago 49
Linux Question

linux ancillary data for sharing and closing of file descriptors

The linux ancillary data can be used to share file descriptors across multiple processes in unix over unix domain sockets. The application has 2 processes A & B listening for data on the network, and upon receiving new connection the recipient process (either A or B) accepts the connection. Now support process A accepts the connection, in order to share this new socket descriptor with process B, process A sends ancillary data to process B. This is all fine and ok.

  1. At this point, both processes have the same set of socket descriptors. Now suppose process B closes the socket descriptor for some reason. Then how can process B indicate the same to process A? Can ancillary data method can be used in some way? or there is a better way?

  2. When process A accepts a new connection, lets say new socket descriptor is 4. When the same is shared using ancillary data with process B, will the socket descriptor value be the same as 4? or it can differ across processes when the socket descriptors are shared?

Answer Source

See section 17.4 in “Advanced Programming in the UNIX Environment” for some good information about file descriptor passing (and a nice picture!). In particular:

Technically, we are passing a pointer to an open file table entry from one process to another. This pointer is assigned the first available descriptor in the receiving process. (Saying that we are passing an open descriptor mistakenly gives the impression that the descriptor number in the receiving process is the same as in the sending process, which usually isn't true.)

So when passing a file descriptor from process A to process B, the descriptor numbers can be different. Also process B does not have any information about the descriptor number used in process A.

There is no "built-in" mechanism to pass the information about closing a file descriptor from B back to A. You will need to send a custom message for that purpose.