xref: /csrg-svn/lib/libc/gen/ttyname.c (revision 46597)
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.8 (Berkeley) 02/23/91";
10 #endif /* LIBC_SCCS and not lint */
11 
12 #include <sys/types.h>
13 #include <sys/stat.h>
14 #include <fcntl.h>
15 #include <dirent.h>
16 #include <sgtty.h>
17 #include <ndbm.h>
18 #include <unistd.h>
19 #include <paths.h>
20 
21 static char buf[sizeof(_PATH_DEV) + MAXNAMLEN] = _PATH_DEV;
22 
23 char *
24 ttyname(fd)
25 	int fd;
26 {
27 	struct stat sb;
28 	struct sgttyb ttyb;
29 	DBM *db;
30 	datum dp, key;
31 	static char *__oldttyname();
32 
33 	/* Must be a terminal. */
34 	if (ioctl(fd, TIOCGETP, &ttyb) < 0)
35 		return(NULL);
36 	/* Must be a character device. */
37 	if (fstat(fd, &sb) || !S_ISCHR(sb.st_mode))
38 		return(NULL);
39 
40 	if (!(db = dbm_open(_PATH_DEVDB, O_RDONLY, 0)))
41 		return(__oldttyname(fd, &sb));
42 	key.dptr = (char *)&sb.st_rdev;
43 	key.dsize = sizeof(sb.st_rdev);
44 	dp = dbm_fetch(db, key);
45 	if (!dp.dptr)
46 		return(__oldttyname(fd, &sb));
47 	bcopy(dp.dptr, buf + sizeof(_PATH_DEV) - 1, dp.dsize);
48 	return(buf);
49 }
50 
51 static char *
52 __oldttyname(fd, sb)
53 	int fd;
54 	struct stat *sb;
55 {
56 	register struct dirent *dirp;
57 	register DIR *dp;
58 	struct stat dsb;
59 	char *rval, *strcpy();
60 
61 	if ((dp = opendir(_PATH_DEV)) == NULL)
62 		return(NULL);
63 
64 	for (rval = NULL; dirp = readdir(dp);) {
65 		if (dirp->d_fileno != sb->st_ino)
66 			continue;
67 		bcopy(dirp->d_name, buf + sizeof(_PATH_DEV) - 1,
68 		    dirp->d_namlen + 1);
69 		if (stat(buf, &dsb) || sb->st_dev != dsb.st_dev ||
70 		    sb->st_ino != dsb.st_ino)
71 			continue;
72 		(void)closedir(dp);
73 		rval = buf;
74 		break;
75 	}
76 	(void)closedir(dp);
77 	return(rval);
78 }
79