08b3564cb2d9611dbf9039045306472323b1b900
[platform/upstream/kbd.git] / src / getfd.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <fcntl.h>
5 #include <errno.h>
6 #include <linux/kd.h>
7 #include <sys/ioctl.h>
8 #include "nls.h"
9 #include "getfd.h"
10
11 /*
12  * getfd.c
13  *
14  * Get an fd for use with kbd/console ioctls.
15  * We try several things because opening /dev/console will fail
16  * if someone else used X (which does a chown on /dev/console).
17  */
18
19 static int
20 is_a_console(int fd) {
21     char arg;
22
23     arg = 0;
24     return (ioctl(fd, KDGKBTYPE, &arg) == 0
25             && ((arg == KB_101) || (arg == KB_84)));
26 }
27
28 static int
29 open_a_console(char *fnam) {
30     int fd;
31
32     fd = open(fnam, O_RDONLY);
33     if (fd < 0 && errno == EACCES)
34       fd = open(fnam, O_WRONLY);
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
44 int getfd() {
45     int fd;
46
47     fd = open_a_console("/dev/tty");
48     if (fd >= 0)
49       return fd;
50
51     fd = open_a_console("/dev/tty0");
52     if (fd >= 0)
53       return fd;
54
55     fd = open_a_console("/dev/vc/0");
56     if (fd >= 0)
57       return fd;
58
59     fd = open_a_console("/dev/console");
60     if (fd >= 0)
61       return fd;
62
63     for (fd = 0; fd < 3; fd++)
64       if (is_a_console(fd))
65         return fd;
66
67     fprintf(stderr,
68             _("Couldnt get a file descriptor referring to the console\n"));
69     exit(1);            /* total failure */
70 }