xref: /csrg-svn/lib/libc/gen/ttyname.c (revision 49247)
11994Swnj /*
235450Sbostic  * Copyright (c) 1988 The Regents of the University of California.
335450Sbostic  * All rights reserved.
435450Sbostic  *
542627Sbostic  * %sccs.include.redist.c%
61994Swnj  */
71994Swnj 
835450Sbostic #if defined(LIBC_SCCS) && !defined(lint)
9*49247Sbostic static char sccsid[] = "@(#)ttyname.c	5.10 (Berkeley) 05/06/91";
1035450Sbostic #endif /* LIBC_SCCS and not lint */
1135450Sbostic 
1235450Sbostic #include <sys/types.h>
131994Swnj #include <sys/stat.h>
1446338Sbostic #include <fcntl.h>
1546338Sbostic #include <dirent.h>
1635450Sbostic #include <sgtty.h>
1747051Sbostic #include <db.h>
1846597Sdonn #include <unistd.h>
1939113Sbostic #include <paths.h>
201994Swnj 
2146338Sbostic static char buf[sizeof(_PATH_DEV) + MAXNAMLEN] = _PATH_DEV;
2246338Sbostic 
231994Swnj char *
2435450Sbostic ttyname(fd)
2535450Sbostic 	int fd;
261994Swnj {
2746338Sbostic 	struct stat sb;
2835450Sbostic 	struct sgttyb ttyb;
2947051Sbostic 	DB *db;
3047051Sbostic 	DBT data, key;
31*49247Sbostic 	struct {
32*49247Sbostic 		mode_t type;
33*49247Sbostic 		dev_t dev;
34*49247Sbostic 	} bkey;
3546338Sbostic 	static char *__oldttyname();
361994Swnj 
3746338Sbostic 	/* Must be a terminal. */
3835450Sbostic 	if (ioctl(fd, TIOCGETP, &ttyb) < 0)
391994Swnj 		return(NULL);
4046338Sbostic 	/* Must be a character device. */
4146338Sbostic 	if (fstat(fd, &sb) || !S_ISCHR(sb.st_mode))
421994Swnj 		return(NULL);
4346338Sbostic 
4447051Sbostic 	if (db = hash_open(_PATH_DEVDB, O_RDONLY, 0, NULL)) {
45*49247Sbostic 		bkey.type = S_IFCHR;
46*49247Sbostic 		bkey.dev = sb.st_rdev;
47*49247Sbostic 		key.data = &bkey;
48*49247Sbostic 		key.size = sizeof(bkey);
4947051Sbostic 		if (!(db->get)(db, &key, &data, 0)) {
5047051Sbostic 			bcopy(data.data,
5147051Sbostic 			    buf + sizeof(_PATH_DEV) - 1, data.size);
5247051Sbostic 			return(buf);
5347051Sbostic 		}
5447051Sbostic 	}
5547051Sbostic 	return(__oldttyname(fd, &sb));
5646338Sbostic }
5746338Sbostic 
5846338Sbostic static char *
5946338Sbostic __oldttyname(fd, sb)
6046338Sbostic 	int fd;
6146338Sbostic 	struct stat *sb;
6246338Sbostic {
6346338Sbostic 	register struct dirent *dirp;
6446338Sbostic 	register DIR *dp;
6546338Sbostic 	struct stat dsb;
6646338Sbostic 	char *rval, *strcpy();
6746338Sbostic 
6839113Sbostic 	if ((dp = opendir(_PATH_DEV)) == NULL)
691994Swnj 		return(NULL);
7046338Sbostic 
7135450Sbostic 	for (rval = NULL; dirp = readdir(dp);) {
7246338Sbostic 		if (dirp->d_fileno != sb->st_ino)
731994Swnj 			continue;
7446338Sbostic 		bcopy(dirp->d_name, buf + sizeof(_PATH_DEV) - 1,
7546338Sbostic 		    dirp->d_namlen + 1);
7646338Sbostic 		if (stat(buf, &dsb) || sb->st_dev != dsb.st_dev ||
7746338Sbostic 		    sb->st_ino != dsb.st_ino)
781994Swnj 			continue;
7946338Sbostic 		(void)closedir(dp);
8035450Sbostic 		rval = buf;
8135450Sbostic 		break;
821994Swnj 	}
8346338Sbostic 	(void)closedir(dp);
8435450Sbostic 	return(rval);
851994Swnj }
86