ttyname() — Get the name of a terminal

Standards

Standards / Extensions C or C++ Dependencies

POSIX.1
XPG4
XPG4.2
Single UNIX Specification, Version 3

both  

Format

#define _POSIX_SOURCE
#include <unistd.h>

char *ttyname(int fildes);

General description

Returns a string containing the path name of the terminal associated with the given file descriptor, fildes. Subsequent calls to ttyname() may overwrite this string, because the pointer returned may point to static data.

Returned value

If successful, ttyname() returns a string containing a path name.

If unsuccessful because fildes is not a terminal, or the path name cannot be determined, ttyname() returns a NULL pointer.

Special behavior for XPG4: The ttyname() function sets errno to one of the following values:
Error Code
Description
EBADF
The fildes argument is not a valid open file descriptor.
ENOTTY
The fildes argument is not associated with a terminal.

Example

CELEBT16
⁄* CELEBT16

   This example provides the pathname of the terminal
   associated with stdin.

 *⁄
#define _POSIX_SOURCE
#include <unistd.h>
#include <stdio.h>

main() {
  char *ret, tty[40];

  if ((ret = ttyname(STDIN_FILENO)) == NULL)
    perror("ttyname() error");
  else {
    strcpy(tty, ret);
    printf("The ttyname associated with my stdin is %s\n", tty);
  }
}
Output
The ttyname associated with my stdin is /dev/ttyp0000

Related information