44#include <stdio.h>
55#include <stdlib.h>
66#include <string.h>
7+ #include <sys/select.h>
78#include <termios.h>
89#include <unistd.h>
910
@@ -51,6 +52,32 @@ static void enableRawMode(void)
5152 tcsetattr (STDIN_FILENO , TCSAFLUSH , & raw );
5253}
5354
55+ static bool read_attr ;
56+
57+ static void listen_keyboard_handler (void )
58+ {
59+ int attr_fd = open (KMLDRV_DEVICE_ATTR_FILE , O_RDWR );
60+ char input ;
61+
62+ if (read (STDIN_FILENO , & input , 1 ) == 1 ) {
63+ char buf [20 ];
64+ switch (input ) {
65+ case 16 :
66+ read (attr_fd , buf , 6 );
67+ buf [0 ] = (buf [0 ] - '0' ) ? '0' : '1' ;
68+ read_attr = !read_attr ;
69+ write (attr_fd , buf , 6 );
70+ break ;
71+ case 17 :
72+ read (attr_fd , buf , 6 );
73+ buf [4 ] = '1' ;
74+ write (attr_fd , buf , 6 );
75+ break ;
76+ }
77+ }
78+ close (attr_fd );
79+ }
80+
5481int main (int argc , char * argv [])
5582{
5683 int c ;
@@ -85,33 +112,38 @@ int main(int argc, char *argv[])
85112 int flags = fcntl (STDIN_FILENO , F_GETFL , 0 );
86113 fcntl (STDIN_FILENO , F_SETFL , flags | O_NONBLOCK );
87114
88- FILE * device_ptr = fopen (KMLDRV_DEVICE_FILE , "r" );
89115 char display_buf [DRAWBUFFER_SIZE ];
90116
91- int attr_fd = open (KMLDRV_DEVICE_ATTR_FILE , O_WRONLY );
92- char input ;
93- while (fgets (display_buf , DRAWBUFFER_SIZE , device_ptr )) {
94- printf ("%s" , display_buf );
95-
96- if (read (STDIN_FILENO , & input , 1 ) == 1 ) {
97- switch (input ) {
98- case 16 :
99- char buf [20 ];
100- read (attr_fd , buf , 5 );
101- buf [0 ] = (buf [0 ] - '0' ) ? '0' : '1' ;
102- write (attr_fd , buf , 5 );
103- break ;
104- case 17 :
105- break ;
106- }
117+ fd_set readset ;
118+ int device_fd = open (KMLDRV_DEVICE_FILE , O_RDONLY );
119+ int max_fd = device_fd > STDIN_FILENO ? device_fd : STDIN_FILENO ;
120+ read_attr = true;
121+
122+ while (1 ) {
123+ FD_ZERO (& readset );
124+ FD_SET (STDIN_FILENO , & readset );
125+ FD_SET (device_fd , & readset );
126+
127+ int result = select (max_fd + 1 , & readset , NULL , NULL , NULL );
128+ if (result < 0 ) {
129+ printf ("Error with select system call\n" );
130+ exit (1 );
131+ }
132+
133+ if (FD_ISSET (STDIN_FILENO , & readset )) {
134+ FD_CLR (STDIN_FILENO , & readset );
135+ listen_keyboard_handler ();
136+ } else if (read_attr && FD_ISSET (device_fd , & readset )) {
137+ FD_CLR (device_fd , & readset );
138+ read (device_fd , display_buf , DRAWBUFFER_SIZE );
139+ printf ("%s" , display_buf );
107140 }
108141 }
109142
110143 disableRawMode ();
111144 fcntl (STDIN_FILENO , F_SETFL , flags );
112145
113- fclose (device_ptr );
114- close (attr_fd );
146+ close (device_fd );
115147
116148 return 0 ;
117149}
0 commit comments