Home  >  Article  >  Backend Development  >  How to Handle Input in Linux: An Alternative to kbhit() and getch()?

How to Handle Input in Linux: An Alternative to kbhit() and getch()?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-28 05:43:30470browse

How to Handle Input in Linux: An Alternative to kbhit() and getch()?

Input Handling in Linux: An Alternative to kbhit() and getch()

In Windows, _kbhit() and _getch() functions provide a simple way to check for keyboard input without halting the program. However, these functions are not available on Linux. This article explores an alternative approach for handling input on Linux.

Morgan Mattews's Code

One solution is to utilize the code provided by Morgan Mattews, which emulates the functionality of _kbhit() in a POSIX-compliant manner. It involves deactivating buffering at the termios level.

getchar() Issue

Disabling termios buffering not only addresses the _kbhit() absence but also tackles the getchar() issue by preventing input buffering.

Example

<code class="c">#include <stdio.h>
#include <termios.h>

int kbhit() {
    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;
}

int main() {
    while (true) {
        if (kbhit()) {
            char c = getchar();
            if (c == 'g') {
                printf("You pressed G\n");
            }
        }
        printf("Running\n");
        sleep(1);
    }

    return 0;
}</code>

The above is the detailed content of How to Handle Input in Linux: An Alternative to kbhit() and getch()?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn