Skip to content

Instantly share code, notes, and snippets.

@bradmartin333
Created October 19, 2024 02:46
Show Gist options
  • Save bradmartin333/939219d4f175306742bc4486dbc8ca22 to your computer and use it in GitHub Desktop.
Save bradmartin333/939219d4f175306742bc4486dbc8ca22 to your computer and use it in GitHub Desktop.
stream keyboard input on a thread
#include <iostream>
#include <thread>
#include <termios.h>
#include <unistd.h>
void processKeyboardInput() {
termios original_settings, new_settings;
tcgetattr(STDIN_FILENO, &original_settings);
new_settings = original_settings;
new_settings.c_lflag &= ~ICANON;
tcsetattr(STDIN_FILENO, TCSAFLUSH, &new_settings);
char key;
while (true) {
key = getchar();
switch (key) {
case '\033':
return;
default:
std::cout << " " << key << std::endl;
break;
}
}
tcsetattr(STDIN_FILENO, TCSAFLUSH, &original_settings);
}
int main() {
std::thread keyboardThread(processKeyboardInput);
std::cout << "Main thread is running." << std::endl;
keyboardThread.join();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment