1 /* 2 * Copyright (c) 1988, 1993 3 * The Regents of the University of California. All rights reserved. 4 * 5 * %sccs.include.redist.c% 6 */ 7 8 #if defined(LIBC_SCCS) && !defined(lint) 9 static char sccsid[] = "@(#)ttyname.c 8.1 (Berkeley) 06/04/93"; 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 <db.h> 18 #include <string.h> 19 #include <paths.h> 20 21 static char buf[sizeof(_PATH_DEV) + MAXNAMLEN] = _PATH_DEV; 22 static char *oldttyname __P((int, struct stat *)); 23 24 char * 25 ttyname(fd) 26 int fd; 27 { 28 struct stat sb; 29 struct sgttyb ttyb; 30 DB *db; 31 DBT data, key; 32 struct { 33 mode_t type; 34 dev_t dev; 35 } bkey; 36 37 /* Must be a terminal. */ 38 if (ioctl(fd, TIOCGETP, &ttyb) < 0) 39 return (NULL); 40 /* Must be a character device. */ 41 if (fstat(fd, &sb) || !S_ISCHR(sb.st_mode)) 42 return (NULL); 43 44 if (db = dbopen(_PATH_DEVDB, O_RDONLY, 0, DB_HASH, NULL)) { 45 bkey.type = S_IFCHR; 46 bkey.dev = sb.st_rdev; 47 key.data = &bkey; 48 key.size = sizeof(bkey); 49 if (!(db->get)(db, &key, &data, 0)) { 50 bcopy(data.data, 51 buf + sizeof(_PATH_DEV) - 1, data.size); 52 (void)(db->close)(db); 53 return (buf); 54 } 55 (void)(db->close)(db); 56 } 57 return (oldttyname(fd, &sb)); 58 } 59 60 static char * 61 oldttyname(fd, sb) 62 int fd; 63 struct stat *sb; 64 { 65 register struct dirent *dirp; 66 register DIR *dp; 67 struct stat dsb; 68 69 if ((dp = opendir(_PATH_DEV)) == NULL) 70 return (NULL); 71 72 while (dirp = readdir(dp)) { 73 if (dirp->d_fileno != sb->st_ino) 74 continue; 75 bcopy(dirp->d_name, buf + sizeof(_PATH_DEV) - 1, 76 dirp->d_namlen + 1); 77 if (stat(buf, &dsb) || sb->st_dev != dsb.st_dev || 78 sb->st_ino != dsb.st_ino) 79 continue; 80 (void)closedir(dp); 81 return (buf); 82 } 83 (void)closedir(dp); 84 return (NULL); 85 } 86