xref: /csrg-svn/lib/libc/gen/ttyname.c (revision 42627)
1 /*
2  * Copyright (c) 1988 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #if defined(LIBC_SCCS) && !defined(lint)
9 static char sccsid[] = "@(#)ttyname.c	5.6 (Berkeley) 06/01/90";
10 #endif /* LIBC_SCCS and not lint */
11 
12 #include <sys/types.h>
13 #include <sys/dir.h>
14 #include <sys/stat.h>
15 #include <sgtty.h>
16 #include <paths.h>
17 
18 char *
19 ttyname(fd)
20 	int fd;
21 {
22 	register struct direct *dirp;
23 	register DIR *dp;
24 	struct stat sb1, sb2;
25 	struct sgttyb ttyb;
26 	static char buf[sizeof(_PATH_DEV) + MAXNAMLEN] = _PATH_DEV;
27 	char *rval, *strcpy();
28 
29 	if (ioctl(fd, TIOCGETP, &ttyb) < 0)
30 		return(NULL);
31 	if (fstat(fd, &sb1) < 0 || (sb1.st_mode&S_IFMT) != S_IFCHR)
32 		return(NULL);
33 	if ((dp = opendir(_PATH_DEV)) == NULL)
34 		return(NULL);
35 	for (rval = NULL; dirp = readdir(dp);) {
36 		if (dirp->d_ino != sb1.st_ino)
37 			continue;
38 		(void)strcpy(buf + sizeof(_PATH_DEV) - 1, dirp->d_name);
39 		if (stat(buf, &sb2) < 0 || sb1.st_dev != sb2.st_dev ||
40 		    sb1.st_ino != sb2.st_ino)
41 			continue;
42 		closedir(dp);
43 		rval = buf;
44 		break;
45 	}
46 	closedir(dp);
47 	return(rval);
48 }
49