| 1 |
/* |
| 2 |
* Unix test code that puts the terminal into raw mode, then echos typed |
| 3 |
* characters to stdout. Derived from sample code in the Stevens book, posted |
| 4 |
* online at http://www.lafn.org/~dave/linux/terminalIO.html. |
| 5 |
*/ |
| 6 |
|
| 7 |
#include <termios.h> |
| 8 |
#include <unistd.h> |
| 9 |
#include <stdlib.h> |
| 10 |
#include <stdio.h> |
| 11 |
#include "FormatChar.h" |
| 12 |
|
| 13 |
static struct termios save_termios; |
| 14 |
static int term_saved; |
| 15 |
|
| 16 |
/* RAW! mode */ |
| 17 |
int tty_raw(int fd) |
| 18 |
{ |
| 19 |
struct termios buf; |
| 20 |
|
| 21 |
if (tcgetattr(fd, &save_termios) < 0) /* get the original state */ |
| 22 |
return -1; |
| 23 |
|
| 24 |
buf = save_termios; |
| 25 |
|
| 26 |
/* echo off, canonical mode off, extended input |
| 27 |
processing off, signal chars off */ |
| 28 |
buf.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG); |
| 29 |
|
| 30 |
/* no SIGINT on BREAK, CR-to-NL off, input parity |
| 31 |
check off, don't strip the 8th bit on input, |
| 32 |
ouput flow control off */ |
| 33 |
buf.c_iflag &= ~(BRKINT | ICRNL | ISTRIP | IXON); |
| 34 |
|
| 35 |
/* clear size bits, parity checking off */ |
| 36 |
buf.c_cflag &= ~(CSIZE | PARENB); |
| 37 |
|
| 38 |
/* set 8 bits/char */ |
| 39 |
buf.c_cflag |= CS8; |
| 40 |
|
| 41 |
/* output processing off */ |
| 42 |
buf.c_oflag &= ~(OPOST); |
| 43 |
|
| 44 |
buf.c_cc[VMIN] = 1; /* 1 byte at a time */ |
| 45 |
buf.c_cc[VTIME] = 0; /* no timer on input */ |
| 46 |
|
| 47 |
if (tcsetattr(fd, TCSAFLUSH, &buf) < 0) |
| 48 |
return -1; |
| 49 |
|
| 50 |
term_saved = 1; |
| 51 |
|
| 52 |
return 0; |
| 53 |
} |
| 54 |
|
| 55 |
|
| 56 |
/* set it to normal! */ |
| 57 |
int tty_reset(int fd) |
| 58 |
{ |
| 59 |
if (term_saved) |
| 60 |
if (tcsetattr(fd, TCSAFLUSH, &save_termios) < 0) |
| 61 |
return -1; |
| 62 |
|
| 63 |
return 0; |
| 64 |
} |
| 65 |
|
| 66 |
|
| 67 |
int main() |
| 68 |
{ |
| 69 |
tty_raw(0); |
| 70 |
|
| 71 |
int count = 0; |
| 72 |
while (true) { |
| 73 |
char ch; |
| 74 |
char buf[16]; |
| 75 |
int actual = read(0, &ch, 1); |
| 76 |
if (actual != 1) { |
| 77 |
perror("read error"); |
| 78 |
break; |
| 79 |
} |
| 80 |
formatChar(buf, ch); |
| 81 |
fputs(buf, stdout); |
| 82 |
fflush(stdout); |
| 83 |
if (ch == 3) // Ctrl-C |
| 84 |
break; |
| 85 |
} |
| 86 |
|
| 87 |
tty_reset(0); |
| 88 |
return 0; |
| 89 |
} |