C++ How to wait for keyboard input for a limited t

2019-08-11 00:34发布

问题:

I want my console application to stop and wait for the user to press a key. If there is no keyboard input after a limited time, let us say 2 seconds, execution should resume.

I know that no solution will be portable across all implementations, but are there at least simple solutions?

Some posts like this one or this one deal with similar issues, but they don’t seem to offer an answer to that specific problem.

If I could use ncurses (which I can't), I would do something like this using the getch() and timeout() functions:

#include <ncurses.h>
int main()
{
    initscr();          // Start curses mode
    cbreak();           // Turn off line buffering
    timeout(2000);      // Wait 2000 ms for user input
    while (true) {
        addstr("You have 2 sec. to press 'q', otherwise ...\n");
        refresh();
        int inKey = getch();
        if (inKey == 'q') break;
    }
    endwin();
    return 0;
}

回答1:

One way of doing this would be to use low-level read() (assuming you are on Posix) coupled together with timeout signal. Since read() will exit with EINTR after signal processing, you'd know you reached the timeout.