xref: /csrg-svn/lib/libc/gen/devname.c (revision 45036)
1 /*
2  * Copyright (c) 1989 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[] = "@(#)devname.c	5.6 (Berkeley) 08/17/90";
10 #endif /* LIBC_SCCS and not lint */
11 
12 #include <sys/types.h>
13 #include <sys/stat.h>
14 #include <sys/file.h>
15 #include <dirent.h>
16 #include <paths.h>
17 
18 static struct devs {
19 	struct	devs *next;
20 	dev_t	dev;
21 	char	name[MAXNAMLEN+1];
22 	mode_t	type;
23 };
24 
25 #define	hash(x)	((x)&0xff)
26 static struct devs *devhash[0xff + 1];
27 
28 static int devinit;
29 
30 char *
31 devname(dev, type)
32 	dev_t dev;
33 	mode_t type;
34 {
35 	struct devs *devp;
36 
37 	if (devinit == 0) {
38 		register struct devs *devpp;
39 		register struct dirent *entry;
40 		struct stat sb;
41 		DIR *dp = opendir(_PATH_DEV);
42 		int savewd = open(".", O_RDONLY, 0);
43 		mode_t specialtype;
44 
45 		if (savewd == -1 || dp == NULL || chdir(_PATH_DEV) == -1)
46 			return (NULL);
47 		while ((entry = readdir(dp)) != NULL) {
48 			if (stat(entry->d_name, &sb) == -1)
49 				continue;
50 			switch(sb.st_mode&S_IFMT) {
51 			case S_IFCHR:
52 				specialtype = S_IFCHR;
53 				break;
54 			case S_IFBLK:
55 				specialtype = S_IFBLK;
56 				break;
57 			default:
58 				continue;
59 			}
60 			devp = (struct devs *)malloc(sizeof (struct devs));
61 			if (devp == NULL)
62 				return (NULL);
63 			devp->type = specialtype;
64 			devp->dev = sb.st_rdev;
65 			strcpy(devp->name, entry->d_name);
66 			devp->next = NULL;
67 			if ((devpp = devhash[hash(sb.st_rdev)]) == NULL)
68 				devhash[hash(sb.st_rdev)] = devp;
69 			else {
70 				for (;devpp->next != NULL; devpp = devpp->next)
71 					;
72 				devpp->next = devp;
73 			}
74 		}
75 		fchdir(savewd);
76 		close(savewd);
77 		closedir(dp);
78 		devinit = 1;
79 	}
80 	for (devp = devhash[hash(dev)]; devp != NULL; devp = devp->next)
81 		if (dev == devp->dev && type == devp->type)
82 			return(devp->name);
83 
84 	return (NULL);
85 }
86 
87 #ifdef TEST
88 main() {
89 	printf(" %s \n", devname(0));
90 }
91 #endif
92