ttyname.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #include <errno.h>
  2. #include <unistd.h>
  3. #include <string.h>
  4. #include <sys/stat.h>
  5. #include <dirent.h>
  6. static int __check_dir_for_tty_match(char * dirname, struct stat *st, char *buf, size_t buflen)
  7. {
  8. DIR *fp;
  9. int len;
  10. struct stat dst;
  11. struct dirent *d;
  12. fp = opendir(dirname);
  13. if (fp == NULL)
  14. return errno;
  15. strncpy(buf, dirname, buflen);
  16. strncat(buf, "/", buflen);
  17. len = strlen(dirname) + 1;
  18. while ((d = readdir(fp)) != 0) {
  19. strncpy(buf+len, d->d_name, buflen);
  20. buf[buflen]='\0';
  21. if (stat(buf, &dst) == 0 && st->st_dev == dst.st_dev
  22. && st->st_ino == dst.st_ino)
  23. {
  24. closedir(fp);
  25. return 0;
  26. }
  27. }
  28. closedir(fp);
  29. return ENOTTY;
  30. }
  31. /* This is a fairly slow approach. We do a linear search through some
  32. * directories looking for a match. Yes this is lame. But it should
  33. * work, should be small, and will return names that match what is on
  34. * disk. Another approach we could use would be to use the info in
  35. * /proc/self/fd, but that is even more lame since it requires /proc */
  36. char *ttyname(int fd)
  37. {
  38. static char name[NAME_MAX];
  39. ttyname_r(fd, name, NAME_MAX);
  40. return(name);
  41. }
  42. int ttyname_r(int fd, char *buf, size_t buflen)
  43. {
  44. int noerr;
  45. struct stat st;
  46. noerr = errno;
  47. if (buf==NULL) {
  48. noerr = EINVAL;
  49. goto cool_found_it;
  50. }
  51. /* Make sure we have enough space to return "/dev/pts/0" */
  52. if (buflen < 10) {
  53. noerr = ERANGE;
  54. goto cool_found_it;
  55. }
  56. if (!isatty (fd)) {
  57. noerr = ENOTTY;
  58. goto cool_found_it;
  59. }
  60. if (fstat(fd, &st) < 0)
  61. return errno;
  62. if (!isatty(fd)) {
  63. noerr = ENOTTY;
  64. goto cool_found_it;
  65. }
  66. /* Lets try /dev/vc first (be devfs compatible) */
  67. if ( (noerr=__check_dir_for_tty_match("/dev/vc", &st, buf, buflen)) == 0)
  68. goto cool_found_it;
  69. /* Lets try /dev/tts next (be devfs compatible) */
  70. if ( (noerr=__check_dir_for_tty_match("/dev/tts", &st, buf, buflen)) == 0)
  71. goto cool_found_it;
  72. /* Lets try /dev/pts next */
  73. if ( (noerr=__check_dir_for_tty_match("/dev/pts", &st, buf, buflen)) == 0)
  74. goto cool_found_it;
  75. /* Lets try walking through /dev last */
  76. if ( (noerr=__check_dir_for_tty_match("/dev", &st, buf, buflen)) == 0)
  77. goto cool_found_it;
  78. cool_found_it:
  79. __set_errno(noerr);
  80. return noerr;
  81. }