Line | |
---|
1 | /* ttyname.c POSIX 4.7.2
|
---|
2 | * char *ttyname(int fildes);
|
---|
3 | *
|
---|
4 | * Determines name of a terminal device.
|
---|
5 | */
|
---|
6 |
|
---|
7 | #include <lib.h>
|
---|
8 | #include <sys/stat.h>
|
---|
9 | #include <dirent.h>
|
---|
10 | #include <fcntl.h>
|
---|
11 | #include <stddef.h>
|
---|
12 | #include <string.h>
|
---|
13 | #include <unistd.h>
|
---|
14 |
|
---|
15 | PRIVATE char base[] = "/dev";
|
---|
16 | PRIVATE char path[sizeof(base) + 1 + NAME_MAX]; /* extra 1 for '/' */
|
---|
17 |
|
---|
18 | PUBLIC char *ttyname(fildes)
|
---|
19 | int fildes;
|
---|
20 | {
|
---|
21 | DIR *devices;
|
---|
22 | struct dirent *entry;
|
---|
23 | struct stat tty_stat;
|
---|
24 | struct stat dev_stat;
|
---|
25 |
|
---|
26 | /* Simple first test: file descriptor must be a character device */
|
---|
27 | if (fstat(fildes, &tty_stat) < 0 || !S_ISCHR(tty_stat.st_mode))
|
---|
28 | return (char *) NULL;
|
---|
29 |
|
---|
30 | /* Open device directory for reading */
|
---|
31 | if ((devices = opendir(base)) == (DIR *) NULL)
|
---|
32 | return (char *) NULL;
|
---|
33 |
|
---|
34 | /* Scan the entries for one that matches perfectly */
|
---|
35 | while ((entry = readdir(devices)) != (struct dirent *) NULL) {
|
---|
36 | if (tty_stat.st_ino != entry->d_ino)
|
---|
37 | continue;
|
---|
38 | strcpy(path, base);
|
---|
39 | strcat(path, "/");
|
---|
40 | strcat(path, entry->d_name);
|
---|
41 | if (stat(path, &dev_stat) < 0 || !S_ISCHR(dev_stat.st_mode))
|
---|
42 | continue;
|
---|
43 | if (tty_stat.st_ino == dev_stat.st_ino &&
|
---|
44 | tty_stat.st_dev == dev_stat.st_dev &&
|
---|
45 | tty_stat.st_rdev == dev_stat.st_rdev) {
|
---|
46 | closedir(devices);
|
---|
47 | return path;
|
---|
48 | }
|
---|
49 | }
|
---|
50 |
|
---|
51 | closedir(devices);
|
---|
52 | return (char *) NULL;
|
---|
53 | }
|
---|
Note:
See
TracBrowser
for help on using the repository browser.