1 #include <unistd.h>
2 #include <stdio.h>
3 #include <sys/types.h>
4 #include <sys/stat.h>
5 #include <fcntl.h>
6 #include <linux/input.h>
7 #include <string.h>
8 #include <fcntl.h>
9 #include <dirent.h>
10 #define NOKEY 0
11
12 #define DEV_INPUT_EVENT "/dev/input"
13 #define EVENT_DEV_NAME "event"
14 static int stop = 0;
15
is_event_device(const struct dirent * dir)16 static int is_event_device(const struct dirent *dir) {
17 return strncmp(EVENT_DEV_NAME, dir->d_name, 5) == 0;
18 }
19
scan_devices(void)20 static char* scan_devices(void)
21 {
22 struct dirent **namelist;
23 int i, ndev, devnum;
24 char *filename;
25 int max_device = 0;
26
27 ndev = scandir(DEV_INPUT_EVENT, &namelist, is_event_device, alphasort);
28 if (ndev <= 0)
29 return NULL;
30
31 fprintf(stderr, "Available devices:\n");
32
33 for (i = 0; i < ndev; i++)
34 {
35 char fname[64];
36 int fd = -1;
37 char name[256] = "???";
38
39 snprintf(fname, sizeof(fname),
40 "%s/%s", DEV_INPUT_EVENT, namelist[i]->d_name);
41 fd = open(fname, O_RDONLY);
42 if (fd < 0)
43 continue;
44 ioctl(fd, EVIOCGNAME(sizeof(name)), name);
45 close(fd);
46 if (strncmp(name, "adc-keys", strlen("adc-keys")) != 0)
47 continue;
48
49 fprintf(stderr, "%s: %s\n", fname, name);
50
51 sscanf(namelist[i]->d_name, "event%d", &devnum);
52 if (devnum > max_device)
53 max_device = devnum;
54
55 free(namelist[i]);
56 }
57
58 if (devnum > max_device || devnum < 0)
59 return NULL;
60
61 asprintf(&filename, "%s/%s%d",
62 DEV_INPUT_EVENT, EVENT_DEV_NAME,
63 devnum);
64
65 return filename;
66 }
67
68
main(int argc,const char * argv[])69 int main(int argc, const char *argv[])
70 {
71 int keys_fd;
72 struct input_event t;
73
74 setvbuf(stdout, (char *)NULL, _IONBF, 0);//disable stdio out buffer;
75
76 char *event_name = scan_devices();
77 if (!event_name)
78 return -1;
79
80 keys_fd = open(event_name, O_RDONLY);
81 if(keys_fd<=0)
82 {
83 printf("open %s device error!\n", event_name);
84 return 0;
85 }
86
87 while(1)
88 {
89 if(read(keys_fd,&t,sizeof(t))==sizeof(t)) {
90 if(t.type==EV_KEY)
91 if(t.value==0 || t.value==1)
92 {
93 printf("key%d %s\n",t.code, (t.value)?"Presse":"Released");
94
95 }
96 }
97 }
98 close(keys_fd);
99
100 return 0;
101 }
102
103