/*
 * Read one key pressed by using select()
 * by Hans Schou 2004
 */

#include <stdio.h>
#include <sys/types.h>
#include <termios.h>
#include <stdlib.h>

int main(void) {
	char key;
	int rc;
	fd_set read_set;
	struct termios save_termios, set_termios;
	int fd_keyboard = fileno(stdin);

	printf("Press 'q' to quit program.\n");
	printf("Press any other other key to test.\n");

	/* Set up keyboard, disable canonical mode end echo */
	tcgetattr(fd_keyboard, &save_termios);
	set_termios = save_termios;
	set_termios.c_lflag &= ~(ICANON | ECHO);
	set_termios.c_cc[VMIN] = 1;
	set_termios.c_cc[VTIME] = 0;
    	tcsetattr(fd_keyboard, TCSANOW, &set_termios);

	/* Clear read watch */
	FD_ZERO(&read_set);

	do {
		/* Add keyboard to read watch list */
		FD_SET(fd_keyboard, &read_set);
		/* Start select(), block and wait for input in read_set */
		rc = select(fd_keyboard+1, &read_set, NULL, NULL, NULL);
		printf("ReturnCode: %d\n", rc);
		/* Test for keyboard hit */
		if (rc > 0 && FD_ISSET(fd_keyboard, &read_set)) {
			key = fgetc(stdin);
			printf("Key pressed: %c\n", key );
		}
	} while (key != 'q');

	/* Restore keyboard */
	tcsetattr(fd_keyboard, TCSANOW, &save_termios);
	printf("\n");

	return EXIT_SUCCESS;
}

