getch.c revision e629abc58c2acadc7487ea71c1e063f8f8989199
1/*
2C non-blocking keyboard input
3http://stackoverflow.com/questions/448944/c-non-blocking-keyboard-input
4*/
5
6#include <stdlib.h>
7#include <string.h>
8#include <sys/select.h>
9#include <termios.h>
10#include <unistd.h>
11
12struct termios orig_termios;
13
14void reset_terminal_mode()
15{
16    tcsetattr(0, TCSANOW, &orig_termios);
17}
18
19void set_conio_terminal_mode()
20{
21    struct termios new_termios;
22
23    /* take two copies - one for now, one for later */
24    tcgetattr(0, &orig_termios);
25    memcpy(&new_termios, &orig_termios, sizeof(new_termios));
26
27    /* register cleanup handler, and set the new terminal mode */
28    atexit(reset_terminal_mode);
29    cfmakeraw(&new_termios);
30    new_termios.c_oflag |= OPOST;
31    tcsetattr(0, TCSANOW, &new_termios);
32}
33
34int kbhit()
35{
36    struct timeval tv = { 0L, 0L };
37    fd_set fds;
38    FD_ZERO(&fds); // not in original posting to stackoverflow
39    FD_SET(0, &fds);
40    return select(1, &fds, NULL, NULL, &tv);
41}
42
43int getch()
44{
45    int r;
46    unsigned char c;
47    if ((r = read(0, &c, sizeof(c))) < 0) {
48        return r;
49    } else {
50        return c;
51    }
52}
53
54#if 0
55int main(int argc, char *argv[])
56{
57    set_conio_terminal_mode();
58
59    while (!kbhit()) {
60        /* do some work */
61    }
62    (void)getch(); /* consume the character */
63}
64#endif
65