Get the terminal device name with ttyname
Get the path of the terminal attached to a file descriptor with ttyname or the thread-safe ttyname_r, which returns NULL when it is not a terminal.
Printing which terminal a program runs on, or checking that stdin really is one, comes down to ttyname(). This is an example from ttyname(3p): it takes a file descriptor and returns the path of the terminal device, or NULL when the descriptor is not a terminal.
#include <stdio.h>
#include <unistd.h>
int main(void) {
char buf[64];
int err = ttyname_r(STDIN_FILENO, buf, sizeof buf);
if (err == 0)
printf("stdin is %s\n", buf);
else
printf("stdin is not a terminal (error %d)\n", err);
return 0;
}Run from a terminal, then with input redirected from a file:
stdin is /dev/pts/3
stdin is not a terminal (error 25)Error 25 is ENOTTY on Linux. Prefer ttyname_r over ttyname: the plain function returns a pointer into a static buffer that the next call overwrites, so it is not safe with threads, and POSIX says so. The path is found by searching /dev, which can fail inside a container that has no matching device node, even though isatty says yes. When you only need a yes or no, call isatty(). The pseudo-terminal number will differ on your machine.