Last active
March 17, 2020 16:35
-
-
Save JlnWntr/f053cafb4d5625908ec560243c6eb740 to your computer and use it in GitHub Desktop.
Key polling on Linux in plain C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define KEY_POLL_TEST | |
struct termios poll_before, poll_new; | |
struct timeval poll_tv; | |
fd_set poll_fs; | |
int poll_init(){ | |
poll_tv.tv_usec = POLL_TIMEOUT_MICROSECONDS; | |
poll_tv.tv_sec = POLL_TIMEOUT_SECONDS; | |
if(tcgetattr(STDIN_FILENO, &poll_before) != 0) return 1; | |
poll_new = poll_before; | |
poll_new.c_lflag &= ~(ICANON | ECHO); | |
if(tcsetattr(STDIN_FILENO, TCSANOW, &poll_new) != 0) return 1; | |
return 0; | |
} | |
int poll_close(){ | |
return (tcsetattr(STDIN_FILENO, TCSANOW, &poll_before) == 0) ? 0 : 1; | |
} | |
void poll_set_timeout(unsigned int seconds, unsigned int micro_sec){ | |
poll_tv.tv_usec = micro_sec; | |
poll_tv.tv_sec = seconds; | |
} | |
int poll_key(){ | |
FD_ZERO(&poll_fs); | |
FD_SET(STDIN_FILENO, &poll_fs); | |
select(STDIN_FILENO + 1, &poll_fs, 0, 0, &poll_tv); | |
if (FD_ISSET(STDIN_FILENO, &poll_fs)) return getchar(); | |
else return 0; | |
} | |
#ifdef KEY_POLL_TEST | |
int main(){ | |
poll_init(); | |
while(1){ | |
int c = poll_key(); | |
if(c != 0){ | |
printf("key %d\n", c); | |
if(c == 10) break; | |
} | |
} | |
return poll_close(); | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment