TDE base libraries and programs
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
1.5KB

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <fcntl.h>
  5. #include <errno.h>
  6. #include <sys/ioctl.h>
  7. #include <linux/kd.h>
  8. #include "getfd.h"
  9. /*
  10. * getfd.c
  11. *
  12. * Get an fd for use with kbd/console ioctls.
  13. * We try several things because opening /dev/console will fail
  14. * if someone else used X (which does a chown on /dev/console).
  15. */
  16. static int
  17. is_a_console(int fd) {
  18. char arg;
  19. arg = 0;
  20. return (ioctl(fd, KDGKBTYPE, &arg) == 0
  21. && ((arg == KB_101) || (arg == KB_84)));
  22. }
  23. static int
  24. open_a_console(const char *fnam) {
  25. int fd;
  26. /*
  27. * For ioctl purposes we only need some fd and permissions
  28. * do not matter. But setfont:activatemap() does a write.
  29. */
  30. fd = open(fnam, O_RDWR);
  31. if (fd < 0 && errno == EACCES)
  32. fd = open(fnam, O_WRONLY);
  33. if (fd < 0 && errno == EACCES)
  34. fd = open(fnam, O_RDONLY);
  35. if (fd < 0)
  36. return -1;
  37. if (!is_a_console(fd)) {
  38. close(fd);
  39. return -1;
  40. }
  41. return fd;
  42. }
  43. int getfd(const char *fnam) {
  44. int fd;
  45. if (fnam) {
  46. fd = open_a_console(fnam);
  47. if (fd >= 0)
  48. return fd;
  49. fprintf(stderr,
  50. ("Couldnt open %s\n"), fnam);
  51. exit(1);
  52. }
  53. fd = open_a_console("/dev/tty");
  54. if (fd >= 0)
  55. return fd;
  56. fd = open_a_console("/dev/tty0");
  57. if (fd >= 0)
  58. return fd;
  59. fd = open_a_console("/dev/vc/0");
  60. if (fd >= 0)
  61. return fd;
  62. fd = open_a_console("/dev/console");
  63. if (fd >= 0)
  64. return fd;
  65. for (fd = 0; fd < 3; fd++)
  66. if (is_a_console(fd))
  67. return fd;
  68. fprintf(stderr,
  69. ("Couldnt get a file descriptor referring to the console\n"));
  70. exit(1); /* total failure */
  71. }