AlcapDAQ  1
keyb.c
Go to the documentation of this file.
1 /*
2 kbhit() and getch() for Linux/UNIX
3 Chris Giese <geezer@execpc.com> http://my.execpc.com/~geezer
4 */
5 
6 #ifdef linux
7  #include <sys/time.h> /* struct timeval, select() */
8  #include <termios.h> /* tcgetattr(), tcsetattr() */
9  #include <stdlib.h> /* atexit(), exit() */
10  #include <unistd.h> /* read() */
11  #include <stdio.h> /* printf() */
12  #include <string.h> /* memcpy() */
13 
14 #define CLEARSCR "clear"
15 
16 static struct termios g_old_kbd_mode;
17 
18 /*****************************************************************************/
19 static void cooked(void)
20 {
21  tcsetattr(0, TCSANOW, &g_old_kbd_mode);
22 }
23 
24 static void raw(void)
25 {
26  static char init;
27 
28  struct termios new_kbd_mode;
29 
30  if(init)
31  return;
32 /* put keyboard (stdin, actually) in raw, unbuffered mode */
33  tcgetattr(0, &g_old_kbd_mode);
34  memcpy(&new_kbd_mode, &g_old_kbd_mode, sizeof(struct termios));
35  new_kbd_mode.c_lflag &= ~(ICANON | ECHO);
36  new_kbd_mode.c_cc[VTIME] = 0;
37  new_kbd_mode.c_cc[VMIN] = 1;
38  tcsetattr(0, TCSANOW, &new_kbd_mode);
39 /* when we exit, go back to normal, "cooked" mode */
40  atexit(cooked);
41 
42  init = 1;
43 }
44 
45 /*****************************************************************************/
46 /* SLEEP */
47 /*****************************************************************************/
48 void Sleep(int t) {
49  usleep( t*1000 );
50 }
51 
52 /*****************************************************************************/
53 /* GETCH */
54 /*****************************************************************************/
55 int getch(void)
56 {
57  unsigned char temp;
58 
59  raw();
60  /* stdin = fd 0 */
61  if(read(0, &temp, 1) != 1)
62  return 0;
63  return temp;
64 
65 }
66 
67 
68 /*****************************************************************************/
69 /* KBHIT */
70 /*****************************************************************************/
71 int kbhit()
72 {
73 
74  struct timeval timeout;
75  fd_set read_handles;
76  int status;
77 
78  raw();
79  /* check stdin (fd 0) for activity */
80  FD_ZERO(&read_handles);
81  FD_SET(0, &read_handles);
82  timeout.tv_sec = timeout.tv_usec = 0;
83  status = select(0 + 1, &read_handles, NULL, NULL, &timeout);
84  if(status < 0)
85  {
86  printf("select() failed in kbhit()\n");
87  exit(1);
88  }
89  return (status);
90 }
91 
92 
93 #else // Windows
94 
95  #include <conio.h>
96 #define CLEARSCR "cls"
97 #endif
98