1 /* Determine name of a terminal.
3 Copyright (C) 2010-2024 Free Software Foundation, Inc.
5 This file is free software: you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as
7 published by the Free Software Foundation; either version 2.1 of the
8 License, or (at your option) any later version.
10 This file is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License
16 along with this program. If not, see <https://www.gnu.org/licenses/>. */
18 /* Written by Bruno Haible <bruno@clisp.org>, 2010. */
27 #if defined __ANDROID__
32 ttyname_r (int fd
, char *buf
, size_t buflen
)
35 #if defined __ANDROID__
36 /* On Android, read the result from the /proc file system. */
38 /* We rely on isatty to set errno properly (i.e. EBADF or ENOTTY). */
44 char procfile
[14+11+1];
47 sprintf (procfile
, "/proc/self/fd/%d", fd
);
48 ret
= (buflen
< sizeof (largerbuf
)
49 ? readlink (procfile
, largerbuf
, sizeof (largerbuf
))
50 : readlink (procfile
, buf
, buflen
<= INT_MAX
? buflen
: INT_MAX
));
53 if ((size_t) ret
>= buflen
)
55 if (buflen
< sizeof (largerbuf
))
56 memcpy (buf
, largerbuf
, (size_t) ret
);
57 buf
[(size_t) ret
] = '\0';
61 /* When ttyname_r exists, use it. */
62 /* This code is multithread-safe. */
63 /* On Solaris, ttyname_r always fails if buflen < 128. On OSF/1 5.1,
64 ttyname_r ignores the buffer size and assumes the buffer is large enough.
65 So provide a buffer that is large enough. */
67 # if HAVE_POSIXDECL_TTYNAME_R
69 (buflen
< sizeof (largerbuf
)
70 ? ttyname_r (fd
, largerbuf
, sizeof (largerbuf
))
71 : ttyname_r (fd
, buf
, buflen
<= INT_MAX
? buflen
: INT_MAX
));
74 if (buflen
< sizeof (largerbuf
))
76 size_t namelen
= strlen (largerbuf
) + 1;
79 memcpy (buf
, largerbuf
, namelen
);
83 (buflen
< sizeof (largerbuf
)
84 ? ttyname_r (fd
, largerbuf
, sizeof (largerbuf
))
85 : ttyname_r (fd
, buf
, buflen
<= INT_MAX
? buflen
: INT_MAX
));
90 size_t namelen
= strlen (name
) + 1;
93 memmove (buf
, name
, namelen
);
98 /* Note: This is not multithread-safe. */
105 namelen
= strlen (name
) + 1;
106 if (namelen
> buflen
)
108 memcpy (buf
, name
, namelen
);
111 /* Platforms like mingw: no ttys exist at all. */