kbhit() function (uses termios)

Gene Smith gds at chartertn.net
Mon Sep 8 17:52:20 UTC 2008

Joel Sherrill wrote:
> Gene Smith wrote:
>> The code I am trying to port to rtems uses kbhit() function (you hit a
>> key with no echo and no ENTER/RETURN) to cause an action based on the
>> key pressed. Although I am not a big fan of having important things
>> happen based on an unconfirmed key press, it does not seem to work for
>> me in rtems. kbhit always returns 0 even after I press a key.
>> The 3rd party code is copied from here:
>> http://www.flipcode.com/archives/_kbhit_for_Linux.shtml
>> but with the addition of a flag to turn off echo:
>> term.c_lflag &= ~ECHO;
>> Is there a reason this might not work in rtems?  It works ok in linux.
> The code uses select on a serial port and select only
> works on sockets in RTEMS.  This version uses standard
> termios functionality to get to a non-blocking read.
> http://cboard.cprogramming.com/archive/index.php/t-63166.html
> May not be a perfect fit since it is just an example but it
> uses things that work under RTEMS.
>> Thanks,
>> -gene

Thanks for the explanation and the reference. I finally did this based 
on code from Steven unix programming book and works for me. Since this 
is just for test code, I just stay in the "non-canonical" mode with no 
flipping back and forth.

char kbhit() {
     static int initialized = 0;
     int i;

     if (! initialized) {
         // Use termios to turn off line buffering
         struct termios term;
         if (tcgetattr(STDIN_FILENO, &term) < 0)
           rtems_panic("bad tcgetattr");
         term.c_lflag &= ~(ECHO | ICANON);
	term.c_cc[VMIN] = 0;
	term.c_cc[VTIME] = 0;
         if (tcsetattr(STDIN_FILENO, TCSANOW, &term) < 0)
           rtems_panic("bad tcsetattr");
         initialized = 1;
     if ( read(STDIN_FILENO, &i, 1) > 0 )
         return i;
         return 0;

More information about the users mailing list