Accessing Keyboard Input in Linux Using kbhit() and getch() Equivalents
The provided Windows code utilizes the platform-specific functions _kbhit() and _getch() to monitor for keyboard input without interrupting the program's loop. However, these functions are not available on Linux systems, necessitating alternative approaches.
POSIX-Compliant kbhit() Equivalent
If your Linux system lacks a conio.h header that supports kbhit(), consider leveraging Morgan Mattews's implementation. This solution emulates kbhit() functionality on any POSIX-compliant system.
Resolving getchar() Issues
Deactivating buffering at the termios level resolves not only the kbhit() issue but also addresses any concerns related to getchar() as demonstrated in the provided resource. This approach ensures that input is received immediately without waiting for the Enter keypress.
Integration with Example Code
To adapt the provided example code to Linux systems, consider replacing _kbhit() and _getch() with their POSIX-compliant equivalents. This revised code below demonstrates this integration:
<code class="cpp">#include <termios.h> #include <unistd.h> #include <iostream> int main() { // Disable input buffering termios oldt, newt; tcgetattr(STDIN_FILENO, &oldt); newt = oldt; newt.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &newt); while (true) { if (kbhit()) { char c = getchar(); if (c == 'g') { std::cout << "You pressed G" << std::endl; } } sleep(500); std::cout << "Running" << std::endl; } // Restore input buffering tcsetattr(STDIN_FILENO, TCSANOW, &oldt); return 0; }</code>
This modified code utilizes Mattews's kbhit() implementation and deactivates input buffering to achieve similar functionality as the original Windows code.
The above is the detailed content of How to Achieve Non-Blocking Keyboard Input in Linux: A Guide to kbhit() and getch() Equivalents. For more information, please follow other related articles on the PHP Chinese website!