1 /* Copyright (C) 1991,92,93,96,97,98,2000,2002 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, write to the Free
16 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
23 #include <sys/types.h>
31 static char *getttyname (int fd
, dev_t mydev
, ino_t myino
,
32 int save
, int *dostat
) internal_function
;
35 libc_freeres_ptr (static char *getttyname_name
);
39 getttyname (fd
, mydev
, myino
, save
, dostat
)
46 static const char dev
[] = "/dev";
47 static size_t namelen
;
52 dirstream
= __opendir (dev
);
53 if (dirstream
== NULL
)
59 while ((d
= __readdir (dirstream
)) != NULL
)
60 if (((ino_t
) d
->d_fileno
== myino
|| *dostat
)
61 && strcmp (d
->d_name
, "stdin")
62 && strcmp (d
->d_name
, "stdout")
63 && strcmp (d
->d_name
, "stderr"))
65 size_t dlen
= _D_ALLOC_NAMLEN (d
);
66 if (sizeof (dev
) + dlen
> namelen
)
68 free (getttyname_name
);
69 namelen
= 2 * (sizeof (dev
) + dlen
); /* Big enough. */
70 getttyname_name
= malloc (namelen
);
71 if (! getttyname_name
)
74 /* Perhaps it helps to free the directory stream buffer. */
75 (void) __closedir (dirstream
);
78 *((char *) __mempcpy (getttyname_name
, dev
, sizeof (dev
) - 1))
81 (void) __mempcpy (&getttyname_name
[sizeof (dev
)], d
->d_name
, dlen
);
82 if (stat (getttyname_name
, &st
) == 0
83 #ifdef _STATBUF_ST_RDEV
84 && S_ISCHR (st
.st_mode
) && st
.st_rdev
== mydev
86 && (ino_t
) d
->d_fileno
== myino
&& st
.st_dev
== mydev
90 (void) __closedir (dirstream
);
91 __ttyname
= getttyname_name
;
93 return getttyname_name
;
97 (void) __closedir (dirstream
);
102 /* Return the pathname of the terminal FD is open on, or NULL on errors.
103 The returned storage is good only until the next call to this function. */
116 if (fstat (fd
, &st
) < 0)
119 #ifdef _STATBUF_ST_RDEV
120 name
= getttyname (fd
, st
.st_rdev
, st
.st_ino
, save
, &dostat
);
122 name
= getttyname (fd
, st
.st_dev
, st
.st_ino
, save
, &dostat
);
125 if (!name
&& dostat
!= -1)
128 #ifdef _STATBUF_ST_RDEV
129 name
= getttyname (fd
, st
.st_rdev
, st
.st_ino
, save
, &dostat
);
131 name
= getttyname (fd
, st
.st_dev
, st
.st_ino
, save
, &dostat
);