2.9 Digression: what is the difference between a socket and a pipe?

There are several key differences between a named pipe and a socket.

2.9.1 Intent

A socket is intended for single-server, multiple client applications. This means that a single process listens to a socket, but any number of processes can connect to that listening process. Furthermore, the listening (server) process can maintain a different communication “channel” for each client process.

A pipe, on the other hand, is intended for the communication strictly between two programs. Although multiple processes can write to the same named pipe at the same time, the listening process cannot differentiate who sent it what.

2.9.2 How to open

Named pipes can be opened using the open function just like any regular file. In other words, a program does not need any special procedures to attach itself to a named pipe, for read or for writing.

However, a socket requires special procedures. On the server (listening) side, the system call socket is used to first create an end-point file descriptor (FD). The end-point FD is, then, bound to an address using bind. The system call listen is used to mark the end-point as connectable. Last, accept is used to actually accept incoming connections. Each accepted incoming connection automatically creates a socket instance that represents a connection between two processes (as opposed to the specification of end-points).

A client also needs to first create an end-point FD using socket. However, a client can, then, use connect to initiate a connection to another end-point (the destination). If connect is successful, the end-point FD is the FD of a connection instance.

A named socket is essentially a special kind of end-point address (used by the system function socket) that maps to a path of the file system, as opposed to a network address and port number. In other words, a named socket, such as /tmp/sock can take the place of 127.0.0.1:22 if a server program chooses to have the option to accept connection by named socket.