How to read keyboard input asynchronously

Sometimes it is necessary for console application to read keyboard inputs in asynchronous way.

This short example shows how things are done on Windows and Linux:

#ifdef WIN32
 #include <conio.h>
#else
 #include <sys/time.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>
#endif
int main(int argc, char* argv[])
{
 while(1)
 {
#ifdef WIN32
  if (kbhit()){
   return getc(stdin);
  }else{
   Sleep(1000);
   printf("I am still waiting for your input...\n");
  }
#else
  struct timeval tWaitTime;
  tWaitTime.tv_sec = 1;   //seconds
  tWaitTime.tv_usec = 0;  //microseconds
  fd_set fdInput;
  FD_ZERO(&fdInput);
  FD_SET(STDIN_FILENO, &fdInput);
  int n = (int) STDIN_FILENO + 1;
  if (!select(n, &fdInput, NULL, NULL, &tWaitTime))
  {
   printf("I am still waiting for your input...\n");
  }else
  {
   return getc(stdin);
  }
#endif
 }
 return 0;
}

Both applications work equally fine by waiting for user input while displaying messages once in a second

Leave a Reply