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/>. */
22 #include <sys/types.h>
27 #include <set-freeres.h>
31 static char *getttyname (int fd
, dev_t mydev
, ino_t myino
,
32 int save
, int *dostat
);
35 static char *getttyname_name
;
36 weak_alias (getttyname_name
, __ttyname_freemem_ptr
)
39 getttyname (int fd
, dev_t mydev
, ino_t myino
, int save
, int *dostat
)
41 static const char dev
[] = "/dev";
42 static size_t namelen
;
47 dirstream
= __opendir (dev
);
48 if (dirstream
== NULL
)
54 while ((d
= __readdir (dirstream
)) != NULL
)
55 if (((ino_t
) d
->d_fileno
== myino
|| *dostat
)
56 && strcmp (d
->d_name
, "stdin")
57 && strcmp (d
->d_name
, "stdout")
58 && strcmp (d
->d_name
, "stderr"))
60 size_t dlen
= _D_ALLOC_NAMLEN (d
);
61 if (sizeof (dev
) + dlen
> namelen
)
63 free (getttyname_name
);
64 namelen
= 2 * (sizeof (dev
) + dlen
); /* Big enough. */
65 getttyname_name
= malloc (namelen
);
66 if (! getttyname_name
)
69 /* Perhaps it helps to free the directory stream buffer. */
70 (void) __closedir (dirstream
);
73 *((char *) __mempcpy (getttyname_name
, dev
, sizeof (dev
) - 1))
76 (void) __mempcpy (&getttyname_name
[sizeof (dev
)], d
->d_name
, dlen
);
77 if (stat (getttyname_name
, &st
) == 0
78 #ifdef _STATBUF_ST_RDEV
79 && S_ISCHR (st
.st_mode
) && st
.st_rdev
== mydev
81 && (ino_t
) d
->d_fileno
== myino
&& st
.st_dev
== mydev
85 (void) __closedir (dirstream
);
86 __ttyname
= getttyname_name
;
88 return getttyname_name
;
92 (void) __closedir (dirstream
);
97 /* Return the pathname of the terminal FD is open on, or NULL on errors.
98 The returned storage is good only until the next call to this function. */
110 if (fstat (fd
, &st
) < 0)
113 #ifdef _STATBUF_ST_RDEV
114 name
= getttyname (fd
, st
.st_rdev
, st
.st_ino
, save
, &dostat
);
116 name
= getttyname (fd
, st
.st_dev
, st
.st_ino
, save
, &dostat
);
119 if (!name
&& dostat
!= -1)
122 #ifdef _STATBUF_ST_RDEV
123 name
= getttyname (fd
, st
.st_rdev
, st
.st_ino
, save
, &dostat
);
125 name
= getttyname (fd
, st
.st_dev
, st
.st_ino
, save
, &dostat
);