Skip to content

Instantly share code, notes, and snippets.

@dirtycold
Created October 17, 2022 15:14
Show Gist options
  • Save dirtycold/9f75769301cde2d128da1f10eb8b12df to your computer and use it in GitHub Desktop.
Save dirtycold/9f75769301cde2d128da1f10eb8b12df to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <termios.h>
#include <stdio.h>
#include <fcntl.h>
// Read more
// https://forums.raspberrypi.com/viewtopic.php?t=142867
// https://www.kernel.org/doc/Documentation/input/input-programming.txt
// https://stackoverflow.com/questions/6731317/c-exit-from-infinite-loop-on-keypress/6731427#6731427
// https://web.archive.org/web/20180401093525/http://cc.byexamples.com/2007/04/08/non-blocking-user-input-in-loop-without-ncurses/
// https://man7.org/linux/man-pages/man2/select.2.html
// https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/fcntl.2.html
// Refer: https://cboard.cprogramming.com/c-programming/178177-very-simple-program-impossible-create-mac-post1290358.html#post1290358
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;
}
// Refer: https://stackoverflow.com/a/23035044
static int getch(void)
{
struct termios oldattr, newattr;
int ch;
tcgetattr( STDIN_FILENO, &oldattr );
newattr = oldattr;
newattr.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newattr );
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldattr );
return ch;
}
int main(int argc, char *argv[])
{
while(1)
{
do
{
int c = getch();
printf("C: %02x\n", c);
} while(kbhit());
printf("------\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment