Root/tools/lib/getkey.c

Source at commit 1f003f1c2100f7f3670106fd13df0eaec7a0e4e1 created 4 years 2 months ago.
By Werner Almesberger, atusb/atusb.kicad_pcb: grow RF feed trace to 1.9 mm, for 1.0 mm PCB
1/*
2 * lib/getkey.c - Get single characters from standard input
3 *
4 * Written 2011 by Werner Almesberger
5 * Copyright 2011 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 <errno.h>
20
21
22
23static struct termios old_term;
24
25
26static void restore_term(void)
27{
28    if (tcsetattr(0, TCSAFLUSH, &old_term) < 0)
29        perror("tcsetattr");
30}
31
32
33void get_key_init(void)
34{
35    static int initialized = 0;
36    struct termios term;
37
38    if (initialized)
39        return;
40    initialized = 1;
41
42    if (tcgetattr(0, &old_term) < 0) {
43        perror("tcgetattr");
44        exit(1);
45    }
46    term = old_term;
47    cfmakeraw(&term);
48    if (tcsetattr(0, TCSAFLUSH, &term) < 0) {
49        perror("tcsetattr");
50        exit(1);
51    }
52    atexit(restore_term);
53    if (fcntl(0, F_SETFL, O_NONBLOCK) < 0) {
54        perror("fcntl");
55        exit(1);
56    }
57}
58
59
60char get_key(void)
61{
62    ssize_t got;
63        char ch;
64
65    get_key_init();
66    got = read(0, &ch, 1);
67    if (got == 1)
68        return ch;
69    if (got >= 0) {
70        fprintf(stderr, "unexpected read() return value %d\n",
71            (int) got);
72        exit(1);
73    }
74    if (errno == EAGAIN)
75        return 0;
76    perror("read");
77    exit(1);
78}
79

Archive Download this file



interactive