summaryrefslogtreecommitdiff
path: root/libc/termios/ttyname.c
blob: 9fc4f950cd5bf3976f0aac1debd39ae1a5c1e83c (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
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <dirent.h>

char *
ttyname(fd)
int   fd;
{
   static char dev[] = "/dev";
   struct stat st, dst;
   DIR  *fp;
   struct dirent *d;
   static char name[NAME_MAX];
   int noerr = errno;

   if (fstat(fd, &st) < 0)
      return 0;
   if (!isatty(fd))
   {
      errno = ENOTTY;
      return 0;
   }

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

   while ((d = readdir(fp)) != 0)
   {
      strcpy(name + sizeof(dev), d->d_name);
      if (stat(name, &dst) == 0
         && st.st_dev == dst.st_dev && st.st_ino == dst.st_ino)
      {
	 closedir(fp);
	 errno = noerr;
	 return name;
      }
   }
   closedir(fp);
   errno = noerr;
   return 0;
}