1 | /* Copyright (C) 1991-2023 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 | #include <set-freeres.h> |
23 | #include "ttyname.h" |
24 | |
25 | static char *ttyname_buf = NULL; |
26 | weak_alias (ttyname_buf, __ttyname_freemem_ptr) |
27 | |
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) |
32 | { |
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; |
39 | |
40 | if (ttyname_buf == NULL) |
41 | { |
42 | ttyname_buf = malloc (PATH_MAX); |
43 | if (ttyname_buf == NULL) |
44 | return NULL; |
45 | } |
46 | |
47 | int result = __ttyname_r (fd, ttyname_buf, PATH_MAX); |
48 | if (result != 0) |
49 | { |
50 | __set_errno (result); |
51 | return NULL; |
52 | } |
53 | return ttyname_buf; |
54 | } |
55 | |