home *** CD-ROM | disk | FTP | other *** search
/ Atari FTP / ATARI_FTP_0693.zip / ATARI_FTP_0693 / Mint / mntlib32.zoo / ttyname.c < prev    next >
C/C++ Source or Header  |  1993-06-17  |  2KB  |  93 lines

  1. /*
  2.  * ttyname -- figure out the name of the terminal attached to a file
  3.  * descriptor
  4.  *
  5.  * Written by Eric R. Smith and placed in the public domain.
  6.  */
  7.  
  8. #include <stdio.h>
  9. #include <types.h>
  10. #include <stat.h>
  11. #include <dirent.h>
  12. #include <string.h>
  13. #include <unistd.h>
  14.  
  15. extern int __mint;
  16.  
  17. static int find_ino __PROTO((char *, struct stat *, char *));
  18.  
  19. static char tname[L_ctermid];
  20.  
  21. /* Find the file in directory "dir" that matches "sbuf". Returns 1
  22.  * on success, 0 on failure. Note that "dir" is a prefix, i.e. it
  23.  * should end with "/".
  24.  */
  25.  
  26. static int
  27. find_ino(dir, sb, name)
  28.     char *dir;
  29.     struct stat *sb;
  30.     char *name;
  31. {
  32.     char *where = name;
  33.     DIR *drv;
  34.     struct dirent *next;
  35.     struct stat testsb;
  36.  
  37.     drv = opendir(dir);
  38.     if (!drv) return 0;
  39.  
  40.     while (*dir) {
  41.         *where++ = *dir++;
  42.     }
  43.  
  44.     while ((next = readdir(drv)) != NULL) {
  45.         strcpy(where, next->d_name);
  46.         if (stat(name, &testsb))
  47.             continue;
  48.         if (testsb.st_dev == sb->st_dev &&
  49.             testsb.st_ino == sb->st_ino) {
  50.             closedir(drv);
  51.             return 1;
  52.         }
  53.     }
  54.     closedir(drv);
  55.     return 0;
  56. }
  57.  
  58. char *
  59. ttyname(fd)
  60.     int fd;
  61. {
  62.     char *name;
  63.     struct stat sb;
  64.     extern int isatty();
  65.  
  66.     if (!isatty(fd)) return (char *)0;
  67.  
  68.     if (__mint < 9) {
  69.         if (fd == -2) {
  70.             name = "/dev/aux";
  71.         } else {
  72.             name = "/dev/con";
  73.         }
  74.         strcpy(tname, name);
  75.         return tname;
  76.     }
  77.  
  78.     if (fstat(fd, &sb))
  79.         return (char *)0;
  80.  
  81.     /* try the devices first */
  82.     if (find_ino("/dev/", &sb, tname))
  83.         return tname;
  84.  
  85.     /* hmmm, maybe we're a pseudo-tty */
  86.     if (find_ino("u:/pipe/", &sb, tname))
  87.         return tname;
  88.  
  89.     /* I give up */
  90.     strcpy(tname, "/dev/tty");
  91.     return tname;
  92. }
  93.