#include <stdio.h>
#include <time.h>
#include <signal.h>
#include <sys/types.h>
#ifndef hpux /* BSD style */
# include <sgtty.h>
#else hpux /* HP-UX style (and other System V systems) */
# include <termio.h>
#endif hpux
static int tty_mode = 0;
#ifdef TCGETA
static struct termio orig_tty;
static struct termio new_tty;
#else
static struct sgttyb orig_tty;
static struct sgttyb new_tty;
#endif
cbreak()
{
if (tty_mode == 0)
{
#ifdef TCGETA
ioctl(0, TCGETA, &orig_tty);
#else
ioctl(0, TIOCGETP, &orig_tty);
#endif
tty_mode = 1;
new_tty = orig_tty;
}
#ifdef ICANON
new_tty.c_lflag &= ~(ICANON | ECHO);
new_tty.c_cc[VMIN] = 1;
new_tty.c_cc[VTIME] = 0;
ioctl(0, TCSETA, &new_tty);
#else
new_tty.sg_flags |= CBREAK;
new_tty.sg_flags &= ~ECHO;
ioctl(0, TIOCSETN, &new_tty);
#endif
}
normal()
{
if (tty_mode == 1)
{
#ifdef TCSETA
ioctl(0, TCSETA, &orig_tty);
#else
ioctl(0, TIOCSETN, &orig_tty);
#endif
new_tty = orig_tty;
}
}
int key_pressed();
main()
{
int x=0;
long int loop=1;
/* Setup the terminal. (This is just for a quick example) */
cbreak();
while(loop++) {
/*
* Loop is just to let you know that it's still alive.
*/
if ( (loop % 1234) == 0)
printf("At %ld\n", loop);
if ( (x=key_pressed()) != -1) {
printf("Got one, kp=%c\n",x);
fflush(stdout);
}
/*
* Press 'q' to exit.
*/
if ( x == 'q') {
normal();
exit(0);
}
}
}
/*
* This function will return -1 if no key is available, or the key
* that was pressed by the user. It is checking stdin, without blocking.
*
*/
int key_pressed()
{
int mask=1;
static char keypressed;
struct timeval waittime;
int num_chars_read;
waittime.tv_sec=0;
waittime.tv_usec=0;
if (select(1,&mask,0,0,&waittime)) {
num_chars_read=read(0,&keypressed,1);
if (num_chars_read == 1)
return((int)keypressed);
}
return(-1);
}