Principle of Unix Domain Socket. How does it work?

leokaka picture leokaka · Feb 17, 2013 · Viewed 7.7k times · Source

I am doing a study about Unix domain socket. Especially about how does it work. I googled many times with many keywords but the results are all about API, system calls, how to use it, examples ... . I have read about Pipe and FIFO too because Unix Domain socket is said to be the same with Pipe and FIFO but I still want to know more about the concept/priciples of Unix Domain Socket. How does it work? (Maybe at the kernel level because Wiki say this:"This allows two processes to open the same socket in order to communicate. However, communication occurs entirely within the operating system kernel."

I still wonder why Unix domain Socket documentaries is less than Pipe or FIFO? Maybe because it was born so many years ago?

Could anyone show me any ideas or which books/links to read?

Thanks in advance!

Answer

Unix sockets are used as any other socket types. This means, that socket system calls are used for them. The difference between FIFOs and Unix sockets, is that FIFO use file sys calls, while Unix sockets use socket calls.

Unix sockets are addressed as files. It allows to use file permissions for access control.

Unix sockets are created by socket sys call (while FIFO created by mkfifo). If you need client socket, you call connect, passing it server socket address. If you need server socket, you can bind to assign its address. While, for FIFO open call is used. IO operation is performed by read/write.

Unix socket can distinguish its clients, while FIFO cannot. Info about peer is provided by accept call, it returns address of peer.

Unix sockets are bidirectional. This means that every side can perform both read and write operations. While, FIFOs are unidirectional: it has a writer peer and a reader peer.

Unix sockets create less overhead and communication is faster, than by localhost IP sockets. Packets don't need to go through network stack as with localhost sockets. And as they exists only locally, there is no routing.

If you need more details about, how Unix sockets work at kernel level, please, look at net/unix/af_unix.c file in Linux kernel source.