-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path62-2-do_ttyname.c
86 lines (71 loc) · 1.63 KB
/
62-2-do_ttyname.c
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>
#include <linux/limits.h>
#include <string.h>
char *my_ttyname(int fd)
{
static char res[PATH_MAX];
memset(res, 0, PATH_MAX);
strcpy(res, "/dev/");
if (!isatty(fd))
return NULL;
struct stat fd_stat;
if (fstat(fd, &fd_stat) == -1)
return NULL;
DIR *dev_dir = opendir("/dev");
if (dev_dir == NULL)
return NULL;
while (1)
{
struct dirent *ent;
errno = 0;
ent = readdir(dev_dir);
if (ent == NULL)
{
if (errno == 0)
break;
else
return NULL;
}
char buf[PATH_MAX] = "/dev/";
strcpy(buf + 5, ent->d_name);
struct stat st;
if (stat(buf, &st) == -1)
return NULL;
if (st.st_rdev == fd_stat.st_rdev)
{
strcpy(res + 5, ent->d_name);
return res;
}
}
closedir(dev_dir);
dev_dir = opendir("/dev/pts");
strcpy(res + 4, "/pts");
while (1)
{
struct dirent *ent;
errno = 0;
ent = readdir(dev_dir);
if (ent == NULL)
{
if (errno == 0)
break;
else
return NULL;
}
char buf[PATH_MAX] = "/dev/pts/";
strcpy(buf + 9, ent->d_name);
struct stat st;
if (stat(buf, &st) == -1)
return NULL;
if (st.st_rdev == fd_stat.st_rdev)
{
strcpy(res + 9, ent->d_name);
return res;
}
}
return NULL;
}