ttyname.c 786 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #include <errno.h>
  2. #include <unistd.h>
  3. #include <string.h>
  4. #include <sys/stat.h>
  5. #include <dirent.h>
  6. char *
  7. ttyname(fd)
  8. int fd;
  9. {
  10. static char dev[] = "/dev";
  11. struct stat st, dst;
  12. DIR *fp;
  13. struct dirent *d;
  14. static char name[NAME_MAX];
  15. int noerr = errno;
  16. if (fstat(fd, &st) < 0)
  17. return 0;
  18. if (!isatty(fd))
  19. {
  20. errno = ENOTTY;
  21. return 0;
  22. }
  23. fp = opendir(dev);
  24. if (fp == 0)
  25. return 0;
  26. strcpy(name, dev);
  27. strcat(name, "/");
  28. while ((d = readdir(fp)) != 0)
  29. {
  30. strcpy(name + sizeof(dev), d->d_name);
  31. if (stat(name, &dst) == 0
  32. && st.st_dev == dst.st_dev && st.st_ino == dst.st_ino)
  33. {
  34. closedir(fp);
  35. errno = noerr;
  36. return name;
  37. }
  38. }
  39. closedir(fp);
  40. errno = noerr;
  41. return 0;
  42. }