I'm trying to write a simple program that does a specific task when no key is pressed and does another task when any key is pressed. This is what I have so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
int kbhit (void);
int main()
{
char c;
while(1)
{
while (!kbhit())
{
printf("%d", 0);
}
c = getchar();
printf("%c", c);
if(c == 'x' || c == 'X')
break;
sleep(0);
}
return 0;
}
int kbhit (void)
{
struct timeval tv;
fd_set rdfs;
tv.tv_sec = 0;
tv.tv_usec = 1000;
FD_ZERO(&rdfs);
FD_SET (STDIN_FILENO, &rdfs);
select(STDIN_FILENO+1, &rdfs, NULL, NULL, &tv);
return FD_ISSET(STDIN_FILENO, &rdfs);
}
This implementation is good for detecting a single key press over and over, but if you keep the keyboard key pressed, there are significant gaps between detecting the key press. Even though the key is pressed all the time, 0 is printed to console anyway. For example, output looks something like this if I keep 'W' pressed: 000000000000000WWWWWWWW00000000000000000WWWWWWWW00000000...
How can I fix this so that when a keyboard key is kept pressed, kbhit() always returns 0?