Skip to content
systemcoding.dev
Systems Programming

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.

1 min read
Summarize in AI

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.

tty.cc
#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:

Text
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.

Taggedcposix
Share

More snippets

Systems Programming

Get the page size with sysconf(_SC_PAGESIZE)

Read the memory page size at run time with sysconf(_SC_PAGESIZE) instead of hard-coding 4096, which is wrong on arm64 kernels built with 16K or 64K pages.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.