ptg10805159
Section 18.9 Te rminal Identification 699
number and matching i-node number,we’ve located the desired directory entry.We
could also verify that the two entries have matchingst_rdevfields (the major and
minor device numbers for the terminal device) and that the directory entry is a
character special file. However,since we’ve already verified that the file descriptor
argument is both a terminal device and a character special file, and since a matching
device number and i-node number pair is unique on a UNIX system, there is no need
for the additional comparisons.
The name of our terminal might reside in a subdirectory in/dev.Thus, we might
need to search the entirefile system tree under/dev.Weskip several directories that
might produce incorrect or odd-looking results:/dev/.,/dev/..,and/dev/fd.We
also skip the aliases/dev/stdin,/dev/stdout,and/dev/stderr,since they are
symbolic links to files in/dev/fd.
We can test this implementation with the program shown in Figure18.16.
#include "apue.h"
int
main(void)
{
char *name;
if (isatty(0)) {
name = ttyname(0);
if (name == NULL)
name = "undefined";
}else {
name = "not a tty";
}
printf("fd 0: %s\n", name);
if (isatty(1)) {
name = ttyname(1);
if (name == NULL)
name = "undefined";
}else {
name = "not a tty";
}
printf("fd 1: %s\n", name);
if (isatty(2)) {
name = ttyname(2);
if (name == NULL)
name = "undefined";
}else {
name = "not a tty";
}
printf("fd 2: %s\n", name);
exit(0);
}
Figure 18.16Te st thettynamefunction