Add a Timeout for getchar()

brain56 picture brain56 · Mar 16, 2011 · Viewed 8.7k times · Source

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

What do I do so that when my program reaches the instruction getchar(), it will only wait for a certain amount of time for the user to make a keystroke and if the user does not make a keystroke within the given time limit, the program will "skip" the getchar()?

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

Answer

ThiefMaster picture ThiefMaster · Mar 16, 2011

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