summaryrefslogtreecommitdiff
path: root/libc/termios/ttyname.c
blob: e6c28adc29bb729b4145c9b226f880a6a6222b6b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <dirent.h>

static char * __check_dir_for_tty_match(char * dirname, struct stat *st)
{
    DIR *fp;
    struct stat dst;
    struct dirent *d;
    static char name[NAME_MAX];

    fp = opendir(dirname);
    if (fp == 0)
	return 0;
    strcpy(name, dirname);
    strcat(name, "/");

    while ((d = readdir(fp)) != 0) {
	strcpy(name + strlen(dirname) + 1, d->d_name);
	if (stat(name, &dst) == 0
		&& st->st_dev == dst.st_dev && st->st_ino == dst.st_ino) {
	    closedir(fp);
	    return name;
	}
    }
    closedir(fp);
    return NULL;
}

/* This is a failly slow approach.  We do a linear search through
 * some directories looking for a match.  Yes this is lame.  But 
 * it should work, should be small, and will return names that match
 * what is on disk.  
 *
 * Another approach we could use would be to use the info in /proc/self/fd */
char *ttyname(fd)
int fd;
{
    char *the_name = NULL;
    struct stat st;
    int noerr = errno;

    if (fstat(fd, &st) < 0)
	return 0;

    if (!isatty(fd)) {
	noerr = ENOTTY;
	goto cool_found_it;
    }

    /* Lets try /dev/vc first (be devfs compatible) */
    if ( (the_name=__check_dir_for_tty_match("/dev/vc", &st))) 
	goto cool_found_it;

    /* Lets try /dev/tts next (be devfs compatible) */
    if ( (the_name=__check_dir_for_tty_match("/dev/tts", &st))) 
	goto cool_found_it;

    /* Lets try /dev/pts next */
    if ( (the_name=__check_dir_for_tty_match("/dev/pts", &st))) 
	goto cool_found_it;

    /* Lets try walking through /dev last */
    if ( (the_name=__check_dir_for_tty_match("/dev", &st))) 
	goto cool_found_it;

cool_found_it:
    __set_errno(noerr);
    return the_name;
}