Overview:
-
The function socket.send_fds(), sends file descriptors from one process to another using Unix Domain Sockets - the internals of which are detailed here.
-
Using the socket interface, any two machines that talk TCP/IP can communicate with each other.
-
Unix Domain Protocol uses the same socket interface used for network communication while communicating to a process running in the same machine.
-
Since the Unix domain protocol communicates between two processes in the same machine, traversing the TCP/IP suite at both ends of the communication is avoided which reduces the latency significantly.
-
In Unix, file descriptors can be be passed between two processes using Unix Domain Sockets.
-
When file descriptors are passed through Unix Domain Sockets, Unix recreates the descriptors sent to the other process through kernel. It takes care of the corner cases like closing the handle from the client process before the server receiving it.
-
The socket.sendmsg() is the basic function that takes care of sending all kind information between two sockets, be it TCP/IP or Unix Domain Protocol. The socket.recvmsg() function does the receiving work on client and server sockets.
-
The socket.send_fds() uses socket.sendmsg() to send file descriptors from one Unix domain socket to another.
Example - Client sending file descriptors through a Unix domain socket:
# Example Python program that uses domain # Create a UNIX Domain socket # Connect the socket to the server # Obtain two file descriptors both in read only mode # Append the descriptors to a list # Send the list of file descriptors to the server # Receive data from the Unix Domain Socket sender.close() |
Output:
Server Response: b'Great...have read all the news' Connection closed by server |
Example - Server receiving file descriptors through a Unix domain socket:
# Example Python program that creates # Create a Unix Domain socket # Bind the socket to a path # Enter into listening mode # Start accepting connections # Read file descriptors from a connection # Read from each file descriptor sock.send("Great...have read all the news".encode()) |
Output:
Unix domain socket waiting for client connections... b'news1' b'news2' |