get_console.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Utility routines.
  4. *
  5. * Copyright (C) many different people. If you wrote this, please
  6. * acknowledge your work.
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 2 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program; if not, write to the Free Software
  20. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  21. */
  22. #include <stdio.h>
  23. #include <errno.h>
  24. #include <fcntl.h>
  25. #include <unistd.h>
  26. #include <sys/ioctl.h>
  27. #include "libbb.h"
  28. /* From <linux/kd.h> */
  29. static const int KDGKBTYPE = 0x4B33; /* get keyboard type */
  30. static int open_a_console(const char *fnam)
  31. {
  32. int fd;
  33. /* try read-write */
  34. fd = open(fnam, O_RDWR);
  35. /* if failed, try read-only */
  36. if (fd < 0 && errno == EACCES)
  37. fd = open(fnam, O_RDONLY);
  38. /* if failed, try write-only */
  39. if (fd < 0 && errno == EACCES)
  40. fd = open(fnam, O_WRONLY);
  41. return fd;
  42. }
  43. /*
  44. * Get an fd for use with kbd/console ioctls.
  45. * We try several things because opening /dev/console will fail
  46. * if someone else used X (which does a chown on /dev/console).
  47. */
  48. int get_console_fd(void)
  49. {
  50. int fd;
  51. static const char * const choise_console_names[] = {
  52. CONSOLE_DEV, CURRENT_VC, CURRENT_TTY
  53. };
  54. for (fd = 2; fd >= 0; fd--) {
  55. int fd4name;
  56. int choise_fd;
  57. char arg;
  58. fd4name = open_a_console(choise_console_names[fd]);
  59. chk_std:
  60. choise_fd = fd4name >= 0 ? fd4name : fd;
  61. arg = 0;
  62. if (ioctl(choise_fd, KDGKBTYPE, &arg) == 0)
  63. return choise_fd;
  64. if(fd4name >= 0) {
  65. close(fd4name);
  66. fd4name = -1;
  67. goto chk_std;
  68. }
  69. }
  70. bb_error_msg("Couldn't get a file descriptor referring to the console");
  71. return fd; /* total failure */
  72. }
  73. /* END CODE */
  74. /*
  75. Local Variables:
  76. c-file-style: "linux"
  77. c-basic-offset: 4
  78. tab-width: 4
  79. End:
  80. */