Root/cngt/getkey.c

1/*
2 * getkey.c - Single-key TTY input
3 *
4 * Written 2010 by Werner Almesberger
5 * Copyright 2010 Werner Almesberger
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 */
12
13
14#include <stdlib.h>
15#include <stdio.h>
16#include <unistd.h>
17#include <fcntl.h>
18#include <termios.h>
19#include <sys/types.h>
20
21#include "getkey.h"
22
23
24#define TTY_NAME "/dev/tty"
25
26
27static int tty = -1;
28static struct termios old;
29
30
31static void reset_tty(void)
32{
33    if (tty >= 0)
34        if (tcsetattr(tty, TCSADRAIN, &old) < 0)
35            perror("tcsetattr");
36}
37
38
39static void tty_open(void)
40{
41    struct termios new;
42
43    tty = open(TTY_NAME, O_RDONLY | O_NOCTTY);
44    if (tty < 0) {
45        perror(TTY_NAME);
46        exit(1);
47    }
48
49    if (tcgetattr(tty, &old) < 0) {
50        perror("tcgetattr");
51        exit(1);
52    }
53    atexit(reset_tty);
54
55    new = old;
56    cfmakeraw(&new);
57    if (tcsetattr(tty, TCSANOW, &new) < 0) {
58        perror("tcsetattr");
59        exit(1);
60    }
61}
62
63
64char getkey(void)
65{
66    char buf;
67    ssize_t got;
68
69    if (tty == -1)
70        tty_open();
71    got = read(tty, &buf, 1);
72    if (got < 0) {
73        perror("read");
74        reset_tty();
75        exit(1);
76    }
77    return got ? buf : 0;
78}
79

Archive Download this file

Branches:
master



interactive