x86_64: Reformat elf_machine_rela
[glibc.git] / sysdeps / unix / sysv / linux / ttyname.c
blob55de84171c56c8d0b65d1c37f3a010fcb0f8e454
1 /* Copyright (C) 1991-2024 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
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.
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.
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/>. */
18 #include <errno.h>
19 #include <limits.h>
20 #include <termios.h>
21 #include <stdlib.h>
22 #include <set-freeres.h>
23 #include "ttyname.h"
25 static char *ttyname_buf = NULL;
26 weak_alias (ttyname_buf, __ttyname_freemem_ptr)
28 /* Return the pathname of the terminal FD is open on, or NULL on errors.
29 The returned storage is good only until the next call to this function. */
30 char *
31 ttyname (int fd)
33 /* isatty check, tcgetattr is used because it sets the correct
34 errno (EBADF resp. ENOTTY) on error. Fast error path to avoid the
35 allocation */
36 struct termios term;
37 if (__glibc_unlikely (__tcgetattr (fd, &term) < 0))
38 return NULL;
40 if (ttyname_buf == NULL)
42 ttyname_buf = malloc (PATH_MAX);
43 if (ttyname_buf == NULL)
44 return NULL;
47 int result = __ttyname_r (fd, ttyname_buf, PATH_MAX);
48 if (result != 0)
50 __set_errno (result);
51 return NULL;
53 return ttyname_buf;