CSC112 Spring 2016 Examples
#include <stdio.h>1#include <unistd.h>2#include <termios.h>3#include <sys/ioctl.h>4#include <stdlib.h>5#include <sys/poll.h>6#include <stropts.h>789int getkey()10{11char k;1213read(STDIN_FILENO, &k, 1);1415return k;16}171819int hasInput()20{21struct pollfd fds;22int pres;2324fds.fd=STDIN_FILENO;25fds.events=POLLIN;26pres = poll(&fds, 1, 0);2728return pres==1;29}30313233void setMode(int _echo, int _canonical, int _signal, int _special)34{35struct termios t;3637//get the current termios38if(tcgetattr(STDIN_FILENO, &t) == -1) {39return; //TODO Exception Handling40}414243//echo handling44if(_echo) {45//set the ECHO flag46t.c_lflag |= ECHO;47} else {48//clear the ECHO flag49t.c_lflag &= ~ECHO;50}5152//canonical handling53if(_canonical) {54t.c_lflag |= ICANON;55t.c_iflag |= ICRNL;56} else {57t.c_lflag &= ~ICANON;58t.c_iflag &= ~ICRNL;59}6061//singal handling62if(_signal) {63t.c_lflag |= ISIG | IEXTEN;64} else {65t.c_lflag &= ~(ISIG | IEXTEN);66}676869//special processing handling70if(_special) {71t.c_iflag |= BRKINT | INPCK | IGNBRK | ISTRIP | IGNCR | IXON | INLCR | PARMRK;72t.c_oflag |= OPOST;73} else {74t.c_iflag &= ~(BRKINT | INPCK | IGNBRK | ISTRIP | IGNCR | IXON | INLCR | PARMRK);75t.c_oflag &= ~OPOST;76}7778t.c_cc[VMIN] = 1;79t.c_cc[VTIME] = 0;8081//set the ttye info82if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &t) == -1)83return; //TODO exception handling84}858687int main()88{89int x;9091setMode(0, 0, 1, 1);9293do {94x = getkey();95printf("%d\n", x);96usleep(30000);97} while(hasInput());98return 0;99}100101102