ttyfd.c 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. #include <fcntl.h>
  2. #include <stdio.h>
  3. #include <unistd.h>
  4. #include "ttyfd.h"
  5. /**
  6. * ttyfd(void):
  7. * Attempt to return a file descriptor to the attached terminal. In order of
  8. * priority, try to open the terminal device, as returned by ctermid(3); then
  9. * use standard error, standard input, or standard output if any of them are
  10. * terminals.
  11. */
  12. int
  13. ttyfd(void)
  14. {
  15. char ttypath[L_ctermid];
  16. int fd;
  17. /* Ask for a path to the TTY device. */
  18. ctermid(ttypath);
  19. /* If we got a path, try to open it. */
  20. if (ttypath[0] != '\0') {
  21. if ((fd = open(ttypath, O_WRONLY | O_NOCTTY)) != -1)
  22. return (fd);
  23. }
  24. /*
  25. * Use standard error/input/output if one of them is a terminal. We
  26. * don't check for dup failing because if it fails once it's going to
  27. * fail every time.
  28. */
  29. if (isatty(STDERR_FILENO))
  30. return (dup(STDERR_FILENO));
  31. if (isatty(STDIN_FILENO))
  32. return (dup(STDIN_FILENO));
  33. if (isatty(STDOUT_FILENO))
  34. return (dup(STDOUT_FILENO));
  35. /* Sorry, couldn't produce a terminal descriptor. */
  36. return (-1);
  37. }