00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018 #include <stdio.h>
00019 #include <stdlib.h>
00020 #include <string.h>
00021 #include <sys/poll.h>
00022 #include <termios.h>
00023 #include <unistd.h>
00024 #include <sys/time.h>
00025 #include <sys/types.h>
00026 #include <sys/stat.h>
00027 #include <fcntl.h>
00028 #include <errno.h>
00029
00030 static struct termios term_attribs, term_attribs_old;
00031
00032 static void restore_term(void)
00033 {
00034 if(tcsetattr(STDIN_FILENO, TCSAFLUSH, &term_attribs_old) < 0)
00035 {
00036 perror("tcsetattr: ");
00037 exit(-1);
00038 }
00039 }
00040
00041 int _kbhit()
00042 {
00043 static int initialized;
00044
00045 fd_set rfds;
00046 struct timeval tv;
00047 int retcode;
00048
00049 if(!initialized)
00050 {
00051 if(tcgetattr(STDIN_FILENO, &term_attribs) < 0)
00052 {
00053 perror("tcgetattr: ");
00054 exit(-1);
00055 }
00056
00057 term_attribs_old = term_attribs;
00058
00059 if(atexit(restore_term))
00060 {
00061 perror("atexit: ");
00062 exit(-1);
00063 }
00064
00065 term_attribs.c_lflag &= ~(ECHO | ICANON | ISIG | IEXTEN);
00066 term_attribs.c_iflag &= ~(IXON | BRKINT | INPCK | ICRNL | ISTRIP);
00067 term_attribs.c_cflag &= ~(CSIZE | PARENB);
00068 term_attribs.c_cflag |= CS8;
00069 term_attribs.c_cc[VTIME] = 0;
00070 term_attribs.c_cc[VMIN] = 0;
00071
00072 if(tcsetattr(STDIN_FILENO, TCSANOW, &term_attribs) < 0)
00073 {
00074 perror("tcsetattr: ");
00075 exit(-1);
00076 }
00077
00078 initialized = 1;
00079 }
00080
00081 FD_ZERO(&rfds);
00082 FD_SET(STDIN_FILENO, &rfds);
00083 memset(&tv, 0, sizeof(tv));
00084
00085 retcode = select(1, &rfds, NULL, NULL, &tv);
00086 if(retcode == -1 && errno == EINTR)
00087 {
00088 return 0;
00089 }
00090 else if(retcode < 0)
00091 {
00092 perror("select: ");
00093 exit(-1);
00094 }
00095 else if(FD_ISSET(STDIN_FILENO, &rfds))
00096 {
00097 return retcode;
00098 }
00099
00100 return 0;
00101 }
00102
00103 int getch()
00104 {
00105 fd_set rfds;
00106 int retcode;
00107
00108 FD_ZERO(&rfds);
00109 FD_SET(STDIN_FILENO, &rfds);
00110
00111 retcode = select(1, &rfds, NULL, NULL, NULL);
00112 if(retcode == -1 && errno == EINTR)
00113 {
00114 return 0;
00115 }
00116 else if(retcode < 0)
00117 {
00118 perror("select: ");
00119 exit(-1);
00120 }
00121
00122 return getchar();
00123 }
00124