TTY Command – Do ‘tty’ Command and ‘/dev/tty’ File Refer to the Controlling Terminal?

ptytty

  1. From man tty

    tty – print the file name of the terminal connected to standard input

    $ tty
    /dev/pts/2
    
  2. From APUE:

    Historically, the name of the controlling terminal in most versions of the UNIX System has been /dev/tty. POSIX.1 provides a
    runtime
    function that we can call to determine the name of the controlling
    terminal.

    #include <stdio.h>
    char *ctermid(char *ptr);
    
    $ ls -la /dev/tty
    crw-rw-rw- 1 root tty 5, 0 May 26 00:16 /dev/tty
    

So I was wondering if the output of command tty and the file /dev/tty both refer to the controlling terminal of the current bash process?

If yes, why does command tty output a pseudoterminal slave file /dev/pts/2, which is different from /dev/tty?

Since the terminal emulator lxterminal and the bash shell running in it use a pseudoterminal pair, isn't the pseudoterminal slave /dev/pts/2 the controlling terminal of the bash shell?

/dev/tty and /dev/pts/2 aren't symlinks to one another, so are they different files?

Thanks.

A follow up post what relations are between my current controlling terminal and `/dev/tty`?

Best Answer

The command tty (1) returns the name of the terminal connected to standard input. This may be the controlling terminal or it may not be. The process may even have a controlling terminal but it is not written in stone that that terminal must be connected to standard input.

From the POSIX manual page for tty (1):

The tty utility shall write to the standard output the name of the terminal that is open as standard input. The name that is used shall be equivalent to the string that would be returned by the ttyname() function defined in the System Interfaces volume of POSIX.1‐2008.

Try it for yourself; run

< /dev/null sh -c 'tty; sleep 10; echo "Done."'

and press Ctrl+C after seeing the message "not a tty" written out by tty because standard input it not a (pseudo-)terminal.

On the other hand, /dev/tty is always a synonim for the controlling terminal of a process, provided that the process actually has a controlling terminal.