1 /* Copyright (C) 1991-2020 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>
29 # define MIN(a, b) ((a) < (b) ? (a) : (b))
32 static const char dev
[] = "/dev";
34 static int getttyname_r (int fd
, char *buf
, size_t buflen
,
35 dev_t mydev
, ino_t myino
, int save
,
39 getttyname_r (int fd
, char *buf
, size_t buflen
, dev_t mydev
, ino_t myino
,
40 int save
, int *dostat
)
46 dirstream
= __opendir (dev
);
47 if (dirstream
== NULL
)
53 while ((d
= __readdir (dirstream
)) != NULL
)
54 if (((ino_t
) d
->d_fileno
== myino
|| *dostat
)
55 && strcmp (d
->d_name
, "stdin")
56 && strcmp (d
->d_name
, "stdout")
57 && strcmp (d
->d_name
, "stderr"))
60 size_t needed
= _D_EXACT_NAMLEN (d
) + 1;
65 (void) __closedir (dirstream
);
70 cp
= __stpncpy (&buf
[sizeof (dev
)], d
->d_name
, needed
);
73 if (stat (buf
, &st
) == 0
74 #ifdef _STATBUF_ST_RDEV
75 && S_ISCHR (st
.st_mode
) && st
.st_rdev
== mydev
77 && (ino_t
) d
->d_fileno
== myino
&& st
.st_dev
== mydev
81 (void) __closedir (dirstream
);
87 (void) __closedir (dirstream
);
89 /* It is not clear what to return in this case. `isatty' says FD
90 refers to a TTY but no entry in /dev has this inode. */
94 /* Store at most BUFLEN character of the pathname of the terminal FD is
95 open on in BUF. Return 0 on success, otherwise an error number. */
97 __ttyname_r (int fd
, char *buf
, size_t buflen
)
104 /* Test for the absolute minimal size. This makes life easier inside
108 __set_errno (EINVAL
);
112 if (buflen
< (int) (sizeof (dev
) + 1))
114 __set_errno (ERANGE
);
120 __set_errno (ENOTTY
);
124 if (fstat (fd
, &st
) < 0)
127 /* Prepare the result buffer. */
128 memcpy (buf
, dev
, sizeof (dev
) - 1);
129 buf
[sizeof (dev
) - 1] = '/';
130 buflen
-= sizeof (dev
);
132 #ifdef _STATBUF_ST_RDEV
133 ret
= getttyname_r (fd
, buf
, buflen
, st
.st_rdev
, st
.st_ino
, save
,
136 ret
= getttyname_r (fd
, buf
, buflen
, st
.st_dev
, st
.st_ino
, save
,
140 if (ret
&& dostat
!= -1)
143 #ifdef _STATBUF_ST_RDEV
144 ret
= getttyname_r (fd
, buf
, buflen
, st
.st_rdev
, st
.st_ino
,
147 ret
= getttyname_r (fd
, buf
, buflen
, st
.st_dev
, st
.st_ino
,
155 weak_alias (__ttyname_r
, ttyname_r
)