Is there a way to limit the wait time for blocking functions, such as getch() ?

  • one
    There is no language. By means of OS, of course (dependent on OS) - avp

2 answers 2

waiting time for blocking functions

There are various blocking functions ...

For example, the select function has the ability to track the timeout.

The getch function does not exist at all. There are getc () and getchar () . Both are blocking and do not have built-in timeout processing.

In order to organize a timeout for such operations, it is necessary:

  1. At the beginning of the program, using the signal () function, set the response to the signal SIGALRM
  2. Just before the call to getc (), set the timeout value by the setitimer function
  3. Immediately after the call to getc (), reset the timeout.
  • I think it is not correct to say that getch () does not exist if it is not in the standard language. As part of conio.h, it is quite self-existing :) Yes, and in a little more detail, what does it mean to “reset the timeout”? - Shadr
  • What does it mean to reset the timeout? - when we call setitimer , we pass it a parameter of type struct itimerval . In this structure, there are two fields that define the time to the first SIGALRM and the interval between successive ones. If both values ​​are reset, then it will stop the generation of signals - RESET timeout. - Sergey

There is a kbhit() function that checks for the presence of a character in the keyboard buffer. Then your program will look like this.

 char ch = 0; while (!kbhit()) { if (timeout) break; } if (kbhit()) ch = getch(); printf("Read char '%c'\n", ch); 
  • Nuuuuu ... while (!kbhit()) is an idle cycle, it chases the processor in vain. - VladD