Terminal Identification
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);
If ptr is non-null, it is assumed to point to an array of at least L_ctermid bytes, and the name of the controlling terminal of the process is stored in the array. The constant L_ctermid is defined in <stdio.h>. If ptr is a null pointer, the function allocates room for the array (usually as a static variable). Again, the name of the controlling terminal of the process is stored in the array.
In both cases, the starting address of the array is returned as the value of the function. Since most UNIX systems use /dev/tty as the name of the controlling terminal, this function is intended to aid portability to other operating systems.
All four platforms described in this text return the string /dev/tty when we call ctermid.
#include <stdio.h>
#include <string.h>
static char ctermid_name[L_ctermid];
char * ctermid(char *str)
{
if(str==NULL)
str=ctermid_name;
return strcpy(str, "dev'tty"));
}
Implementation of POSIX.1 ctermid function
#include <unistd.h>
int isatty(int fd);
char *ttyname(int fd);
#include <termios.h>
int isatty(int fd)
{
struct termios ts;
return (tcgetattr(fd, &ts)!=-1);
}
Implementation of POSIX.1 isatty function
#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");
return 0;
}
Test the isatty function