Commit | Line | Data |
---|---|---|
b11ade1b | 1 | /* |
0655850e KB |
2 | * Copyright (c) 1988 The Regents of the University of California. |
3 | * All rights reserved. | |
4 | * | |
269a7923 | 5 | * %sccs.include.redist.c% |
b11ade1b BJ |
6 | */ |
7 | ||
0655850e | 8 | #if defined(LIBC_SCCS) && !defined(lint) |
23190f83 | 9 | static char sccsid[] = "@(#)ttyname.c 5.14 (Berkeley) %G%"; |
0655850e KB |
10 | #endif /* LIBC_SCCS and not lint */ |
11 | ||
12 | #include <sys/types.h> | |
b11ade1b | 13 | #include <sys/stat.h> |
17bdadd6 KB |
14 | #include <fcntl.h> |
15 | #include <dirent.h> | |
0655850e | 16 | #include <sgtty.h> |
ab225a7a | 17 | #include <db.h> |
23190f83 | 18 | #include <string.h> |
8733b48c | 19 | #include <paths.h> |
b11ade1b | 20 | |
17bdadd6 | 21 | static char buf[sizeof(_PATH_DEV) + MAXNAMLEN] = _PATH_DEV; |
23190f83 | 22 | static char *oldttyname __P((int, struct stat *)); |
17bdadd6 | 23 | |
b11ade1b | 24 | char * |
0655850e KB |
25 | ttyname(fd) |
26 | int fd; | |
b11ade1b | 27 | { |
17bdadd6 | 28 | struct stat sb; |
0655850e | 29 | struct sgttyb ttyb; |
ab225a7a KB |
30 | DB *db; |
31 | DBT data, key; | |
311ace63 KB |
32 | struct { |
33 | mode_t type; | |
34 | dev_t dev; | |
35 | } bkey; | |
b11ade1b | 36 | |
17bdadd6 | 37 | /* Must be a terminal. */ |
0655850e | 38 | if (ioctl(fd, TIOCGETP, &ttyb) < 0) |
23190f83 | 39 | return (NULL); |
17bdadd6 KB |
40 | /* Must be a character device. */ |
41 | if (fstat(fd, &sb) || !S_ISCHR(sb.st_mode)) | |
23190f83 | 42 | return (NULL); |
17bdadd6 | 43 | |
46430cc9 | 44 | if (db = dbopen(_PATH_DEVDB, O_RDONLY, 0, DB_HASH, NULL)) { |
311ace63 KB |
45 | bkey.type = S_IFCHR; |
46 | bkey.dev = sb.st_rdev; | |
47 | key.data = &bkey; | |
48 | key.size = sizeof(bkey); | |
ab225a7a KB |
49 | if (!(db->get)(db, &key, &data, 0)) { |
50 | bcopy(data.data, | |
51 | buf + sizeof(_PATH_DEV) - 1, data.size); | |
5255efff | 52 | (void)(db->close)(db); |
23190f83 | 53 | return (buf); |
ab225a7a | 54 | } |
5255efff | 55 | (void)(db->close)(db); |
ab225a7a | 56 | } |
23190f83 | 57 | return (oldttyname(fd, &sb)); |
17bdadd6 KB |
58 | } |
59 | ||
60 | static char * | |
23190f83 | 61 | oldttyname(fd, sb) |
17bdadd6 KB |
62 | int fd; |
63 | struct stat *sb; | |
64 | { | |
65 | register struct dirent *dirp; | |
66 | register DIR *dp; | |
67 | struct stat dsb; | |
17bdadd6 | 68 | |
8733b48c | 69 | if ((dp = opendir(_PATH_DEV)) == NULL) |
23190f83 | 70 | return (NULL); |
17bdadd6 | 71 | |
9c9a736e | 72 | while (dirp = readdir(dp)) { |
17bdadd6 | 73 | if (dirp->d_fileno != sb->st_ino) |
b11ade1b | 74 | continue; |
17bdadd6 KB |
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) | |
b11ade1b | 79 | continue; |
17bdadd6 | 80 | (void)closedir(dp); |
23190f83 | 81 | return (buf); |
b11ade1b | 82 | } |
17bdadd6 | 83 | (void)closedir(dp); |
23190f83 | 84 | return (NULL); |
b11ade1b | 85 | } |