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.10 (Berkeley) 05/06/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 = hash_open(_PATH_DEVDB, O_RDONLY, 0, 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 return(buf); 53 } 54 } 55 return(__oldttyname(fd, &sb)); 56 } 57 58 static char * 59 __oldttyname(fd, sb) 60 int fd; 61 struct stat *sb; 62 { 63 register struct dirent *dirp; 64 register DIR *dp; 65 struct stat dsb; 66 char *rval, *strcpy(); 67 68 if ((dp = opendir(_PATH_DEV)) == NULL) 69 return(NULL); 70 71 for (rval = NULL; dirp = readdir(dp);) { 72 if (dirp->d_fileno != sb->st_ino) 73 continue; 74 bcopy(dirp->d_name, buf + sizeof(_PATH_DEV) - 1, 75 dirp->d_namlen + 1); 76 if (stat(buf, &dsb) || sb->st_dev != dsb.st_dev || 77 sb->st_ino != dsb.st_ino) 78 continue; 79 (void)closedir(dp); 80 rval = buf; 81 break; 82 } 83 (void)closedir(dp); 84 return(rval); 85 } 86