//-------------------------------------------------------------------
//	rawtty.cpp
//
//	This program sets the terminal into 'raw' mode -- until the
//	user hits the <ESCAPE>-key.  (The numerical value for a key
//	that is pressed is shown in hexadecimal and ascii formats.)
//
//	programmer: ALLAN CRUSE
//	written on: 22 SEP 2003
//-------------------------------------------------------------------

#include <stdio.h>	// for printf(), perror() 
#include <fcntl.h>	// for open() 
#include <stdlib.h>	// for exit() 
#include <unistd.h>	// for read(), write(), close() 
#include <termios.h>	// for tcgetattr(), tcsetattr()

#define ESCAPE_KEY 0x1B

int main( int argc, char **argv )
{
	// save a copy of the current terminal's default settings
	struct termios	orig_termios;
	if ( tcgetattr( STDIN_FILENO, &orig_termios ) < 0 )
		{ perror( "tcgetattr" ); exit(1); }

	// install desired changes using a work-copy of settings
	struct termios	work_termios = orig_termios;
	work_termios.c_lflag &= ~ISIG;
	work_termios.c_lflag &= ~ECHO;
	work_termios.c_lflag &= ~ICANON;
	work_termios.c_cc[ VTIME ] = 0;
	work_termios.c_cc[ VMIN ] = 1;
	tcsetattr( STDIN_FILENO, TCSAFLUSH, &work_termios );

	// perform some keyboard input using 'raw' terminal mode 
	printf( "\nPress any keys.  Hit <ESCAPE> to quit.\n\n" );
	int	done = 0;
	while ( !done )
		{
		int	inch = 0;
		read( STDIN_FILENO, &inch, sizeof( inch ) );
		if ( inch == ESCAPE_KEY ) done = 1;	
		printf( "inch=%08X  ", inch );
		if (( inch >= 0x20 )&&( inch <= 0x7E )) 
			printf( "\'%c\' ", inch );
		printf( "\n" );
		}
	printf( "\n" );	

	// restore the terminal's original default settings
	tcsetattr( STDIN_FILENO, TCSAFLUSH, &orig_termios );
}