ttyname.c 703 B

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