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.13 (Berkeley) 10/17/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 <db.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 DB *db; 30 DBT data, key; 31 struct { 32 mode_t type; 33 dev_t dev; 34 } bkey; 35 static char *__oldttyname(); 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 char *strcpy(); 69 70 if ((dp = opendir(_PATH_DEV)) == NULL) 71 return(NULL); 72 73 while (dirp = readdir(dp)) { 74 if (dirp->d_fileno != sb->st_ino) 75 continue; 76 bcopy(dirp->d_name, buf + sizeof(_PATH_DEV) - 1, 77 dirp->d_namlen + 1); 78 if (stat(buf, &dsb) || sb->st_dev != dsb.st_dev || 79 sb->st_ino != dsb.st_ino) 80 continue; 81 (void)closedir(dp); 82 return(buf); 83 } 84 (void)closedir(dp); 85 return(NULL); 86 } 87