Add timeout for getchar ()

I need to add a timeout function for getchar () in my program.

What should I do when my program reaches the getchar () instruction, it will wait only a certain amount of time for the user to make a key press, and if the user does not press the key for a specified time interval, the program will skip getchar ()?

The operating system does not support the conio.h library, so kbhit is not an option.

+6
source share
2 answers

This is usually achieved by using select()on stdin. Another solution would be to use a alarm()dummy SIGALRM handler to interrupt the call getchar()(POSIX systems only).

+6
source

How to add a timeout when reading from 'stdin' I found this question helpful.

Another method is using multithreading.

If you are using c ++ 11, you can use condition_variable::wait_for()as a timer thread. And the original getchar () is blocked in another thread.

Here is an example:

#include <termios.h>
#include <unistd.h>
#include <thread>
#include <chrono>
#include <iostream>

std::mutex mtx;
std::condition_variable cv;

int ch;
bool INPUT_SIGNAL = false;

void getch ( void ) {
  struct termios oldt, newt;

  tcgetattr ( STDIN_FILENO, &oldt );
  newt = oldt;
  newt.c_lflag &= ~( ICANON | ECHO );

  tcsetattr ( STDIN_FILENO, TCSANOW, &newt );
  ch = getchar();
  tcsetattr ( STDIN_FILENO, TCSANOW, &oldt );

  INPUT_SIGNAL = true;  

  cv.notify_one();
}

void timer ( int period ) {
    for(;;) {
        std::unique_lock<std::mutex> lck(mtx);

        cv.wait_for(lck, std::chrono::seconds(period), []{return INPUT_SIGNAL;});   

        if(INPUT_SIGNAL) {
            INPUT_SIGNAL = false;
            std::cout << ch << "\n";
        } else {
            std::cout << 0 << "\n";
        }
    }
}

int main() {
    std::thread worker(timer, 1);
    for(;;) {
        getch();
    }
    worker.join();
    return 0;
}

When a key is pressed, the main thread notifies the worker thread.

0
source

All Articles