Skip to content

Instantly share code, notes, and snippets.

@jacknlliu
Last active October 19, 2016 15:12
Show Gist options
  • Select an option

  • Save jacknlliu/787c804450e0df4f178b46628ac38cf0 to your computer and use it in GitHub Desktop.

Select an option

Save jacknlliu/787c804450e0df4f178b46628ac38cf0 to your computer and use it in GitHub Desktop.
Listen and get keyboard input with nonblock way
#ifdef __WIN32
#include <conio.h>
#include <stdio.h>
#else
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
int kbhit(void)
{
struct termios oldt, newt;
int ch;
int oldf;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
fcntl(STDIN_FILENO, F_SETFL, oldf);
if(ch != EOF) {
ungetc(ch, stdin);
return 1;
}
return 0;
}
#endif
char getKbhit()
{
char ch;
if (kbhit()){
ch = getchar();
return ch;
} else {
return -1;
}
}
int main(void)
{
while ('q' != getKbhit()) {
printf("just print something if no 'q' press\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment