Terminal Identification

In Controlling Terminals and Controlling Processes, we described the ctermid() function, which returns the name of the controlling terminal for a process (usually /dev/tty on UNIX systems). The functions described in this section are also useful for identifying a terminal.

The isatty() function enables us to determine whether a file descriptor, fd, is associated with a terminal (as opposed to some other file type).

#include <unistd.h>

int isatty(int fd);

Note

Returns true (1) if fd is associated with a terminal, otherwise false (0)

The isatty() function is useful in editors and other screen-handling programs that need to determine whether their standard input and output are directed to a terminal.

Given a file descriptor, the ttyname() function returns the name of the associated terminal device.

#include <unistd.h>

char *ttyname(int fd);

Note

Returns pointer to (statically allocated) string containing terminal name, or NULL on error

To find the name of the terminal, ttyname() uses the opendir() and readdir() functions described in Reading Directories: opendir() and readdir() to walk through the directories holding terminal device names, looking at each directory entry until it finds one whose device ID (the st_rdev field of the stat structure) matches that of the device referred to by the file descriptor fd. Terminal device entries normally reside in two directories: /dev and /dev/pts. The /dev directory contains entries for virtual consoles (e.g., /dev/tty1) and BSD pseudoterminals. The /dev/pts directory contains entries for (System V-style) pseudoterminal slave devices. (We describe pseudoterminals in Chapter 64.)

Note

A reentrant version of ttyname() exists in the form of ttyname_r().

The tty(1) command, which displays the name of the terminal referred to by its standard input, is the command-line analog of ttyname().