UNIX 98 pseudoterminals briefly explained

Quite some time ago, I was experimenting with UNIX 98 pseudoterminals. A pseudoterminal is a device (or more specifically, a device pair) that has the same semantics as a regular TTY terminal except that its other end is connected to a process. The device that offers TTY semantics is refered to as the pseudoterminal slave, while the other end is known as the master. In other words, a pseudoterminal can be used to communicate two processes where one of them sees the channel as a TTY. For more information, see pts(4). This is especially useful, e.g. to implement a terminal emulator or a remote login program.

In short, issuing open() on the /dev/ptmx device (PseudoTerminal MultipleXor) results in the creation of a new master-slave device pair. The file descriptor returned by open() refers to the pseudoterminal master; the path to the matching slave end can be obtained via ptsname(). grantpt() should be called before trying to open the slave side in order to set the mode and owner of the device.

Fair enough. I thought that a good exercise would be to combine this with a TCP/IPv4 socket, forwarding traffic between the pseudoterminal master and the socket. In the gist below, select() is also used to wait for incoming data on both ends and two extra pipes + splice() are used to perform zero-copy transfers.