Difference between revisions of "Kbhit"
From Teknologisk videncenter
(Created page with "<source lang=c> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/select.h> #include <termios.h> #include <stdio.h> struct termios orig_termios; void...") |
m |
||
Line 1: | Line 1: | ||
+ | =Python= | ||
+ | See: https://gist.github.com/michelbl/efda48b19d3e587685e3441a74457024 | ||
+ | =C Linux= | ||
<source lang=c> | <source lang=c> | ||
#include <stdlib.h> | #include <stdlib.h> | ||
Line 62: | Line 65: | ||
} | } | ||
</source> | </source> | ||
− | [[Category:C]][[Category:Linux]] | + | [[Category:C]][[Category:Linux]][[Category:Python]] |
Latest revision as of 03:30, 14 September 2024
Python
See: https://gist.github.com/michelbl/efda48b19d3e587685e3441a74457024
C Linux
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/select.h>
#include <termios.h>
#include <stdio.h>
struct termios orig_termios;
void reset_terminal_mode()
{
tcsetattr(0, TCSANOW, &orig_termios);
}
void set_conio_terminal_mode()
{
struct termios new_termios;
/* take two copies - one for now, one for later */
tcgetattr(0, &orig_termios);
memcpy(&new_termios, &orig_termios, sizeof(new_termios));
/* register cleanup handler, and set the new terminal mode */
atexit(reset_terminal_mode);
cfmakeraw(&new_termios);
tcsetattr(0, TCSANOW, &new_termios);
}
int kbhit()
{
struct timeval tv = { 0L, 0L };
fd_set fds;
FD_ZERO(&fds);
FD_SET(0, &fds);
return select(1, &fds, NULL, NULL, &tv) > 0;
}
int getch()
{
int r;
unsigned char c;
if ((r = read(0, &c, sizeof(c))) < 0) {
return r;
} else {
return c;
}
}
int main(int argc, char *argv[])
{
int count = 0;
set_conio_terminal_mode();
while (!kbhit()) {
/* do some work */
printf("NOTHING HAPPENING: %8d\r", count++);
}
int ch = getch(); /* consume the character */
printf("\nYou pressed: %c\n\r", ch);
}