Abstract


Unix Domain Socket Lifecycle


Server Process

  • socket() - creates a new Unix Domain Socket & returns a File Descriptor that can be used to refer to the socket in future system calls
  • bind() - bind the socket to a Pathname, so that the client can connect to it
  • listen() -  mark the socket as passive, so the socket that will accept incoming connection requests
  • accept() - accept an incoming connection. This call blocks until a connection request arrives. Note that this function will error out if listen() is not called beforehand. Importantly, this call creates a new socket that is connected to the peer socket(peer socket = the socket at the other end of the connection, in this case, socket created by client process) and returns a file descriptor associated with it. So, if you want to communicate with the peer socket, you should use the file descriptor returned from accept(), not the file descriptor returned from the call to socket(). The latter socket remains open and is used to accept further connection requests

Client Process

  • socket() -  creates a new Unix Domain Socket & returns a File Descriptor that can be used to refer to the socket in future system calls. Note that by default, a socket created using socket() is marked as active, and can be used in a connect() call to connect to a passive socket
  • connect() - connects to a passive socket on the pathname specified when the server performs the bind(). Note that connect() should be called after listen() is called on the server socket, otherwise it will error. However, it can be called before accept()

Communication takes place

  • read()
  • write()

End

  • close()

Note

Server socket can accept many client connections at the same time.

Code Example

You can refer to this Medium Article that implements UNIX Domain Socket on both the client and server using C.

References