1/* Copyright (C) 1991-2022 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
3
4 The GNU C Library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Lesser General Public
6 License as published by the Free Software Foundation; either
7 version 2.1 of the License, or (at your option) any later version.
8
9 The GNU C Library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Lesser General Public License for more details.
13
14 You should have received a copy of the GNU Lesser General Public
15 License along with the GNU C Library; if not, see
16 <https://www.gnu.org/licenses/>. */
17
18#include <errno.h>
19#include <limits.h>
20#include <termios.h>
21#include <stdlib.h>
22
23#include "ttyname.h"
24
25static char *ttyname_buf = NULL;
26
27libc_freeres_fn (free_mem)
28{
29 free (ptr: ttyname_buf);
30}
31
32/* Return the pathname of the terminal FD is open on, or NULL on errors.
33 The returned storage is good only until the next call to this function. */
34char *
35ttyname (int fd)
36{
37 /* isatty check, tcgetattr is used because it sets the correct
38 errno (EBADF resp. ENOTTY) on error. Fast error path to avoid the
39 allocation */
40 struct termios term;
41 if (__glibc_unlikely (__tcgetattr (fd, &term) < 0))
42 return NULL;
43
44 if (ttyname_buf == NULL)
45 {
46 ttyname_buf = malloc (PATH_MAX);
47 if (ttyname_buf == NULL)
48 return NULL;
49 }
50
51 int result = __ttyname_r (fd, ttyname_buf, PATH_MAX);
52 if (result != 0)
53 {
54 __set_errno (result);
55 return NULL;
56 }
57 return ttyname_buf;
58}
59

source code of glibc/sysdeps/unix/sysv/linux/ttyname.c