ptg10805159
Section 18.9 Te rminal Identification 695
Note that we can’t protect against overrunning the caller’s buffer,because we have
no way to determine its size.
Twofunctions that aremoreinteresting for a UNIX system areisatty,which
returns true if a file descriptor refers to a terminal device, andttyname,which returns
the pathname of the terminal device that is open on a file descriptor.
#include <unistd.h>
int isatty(intfd);
Returns: 1 (true) if terminal device, 0 (false) otherwise
char *ttyname(intfd);
Returns: pointer to pathname of terminal,NULLon error
Example —isattyFunction
Theisattyfunction is trivial to implement, as we show in Figure18.13. Wesimply try
one of the terminal-specific functions (that doesn’t change anything if it succeeds) and
look at the return value.
#include <termios.h>
int
isatty(int fd)
{
struct termios ts;
return(tcgetattr(fd, &ts) != -1); /* true if no error (is a tty) */
}
Figure 18.13Implementation of POSIX.1isattyfunction
We test ourisattyfunction with the program in Figure18.14.
#include "apue.h"
int
main(void)
{
printf("fd 0: %s\n", isatty(0)? "tty" : "not a tty");
printf("fd 1: %s\n", isatty(1)? "tty" : "not a tty");
printf("fd 2: %s\n", isatty(2)? "tty" : "not a tty");
exit(0);
}
Figure 18.14Te st theisattyfunction