Linux – BSD-style pseudoterminals vs. UNIX 98 pseudoterminals

linuxptyterminal

Based on what I have read about pseudoterminals in Linux, there are two types of pseudoterminals: BSD-style pseudoterminals (which is deprecated) and UNIX 98 pseudoterminals.

I have created two images that shows my understanding of these two types of pseudoterminals.

The following image shows how the BSD-style pseudoterminals works (please correct me if the image is wrong):

enter image description here

This type of pseudoterminals is not hard to understand, each terminal is connected to a unique master driver.


But in the UNIX 98 pseudoterminals, things are a little more confusing. The following image shows how I think this type of pseudoterminals works:

enter image description here

So basically all terminals use the same master driver (/dev/ptmx), but I am not sure how the master driver knows how to do the following:

  • If data is being sent from one of the terminal processes, how does the master driver knows to which TTY slave driver the data should be passed to?

  • If data is being sent from one of the TTY slave drivers, how does the master driver knows to which terminal process the data should be passed to?

Does the master driver knows how to do this in the way that I have shown in the image (i.e. the master driver have a mapping table that maps each terminal PID to its corresponding TTY slave driver)?

Best Answer

You are curiously fascinated by names. /dev/ptmx is not a "driver", it's just a name in the filesystem, which has a special meaning.

A process opens a new master pty by calling posix_openpt(), which returns a file descriptor; the same effect can be achieved by calling open() on /dev/ptmx. Each time a process calls open() of /dev/ptmx a new pseudoterminal is created; the pseudoterminal is destroyed when there are no more processes having this file descriptor open. This file descriptor refers to the master side of the pseudoterminal, and can be passed to descendant processes like any other file descriptor.

For more detailed information see unix.stackexchange.com/questions/117981. (Hat tip to @JdeBP for the suggestion.)

Once a process has a file descriptor referring to a master side of the pseudoterminal, it can find out the name of the slave side of the pseudoterminal by calling ptsname(), and can pass this name to any process it wants to control through the pseudoterminal.