-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselect-timeout.c
executable file
·91 lines (80 loc) · 1.9 KB
/
select-timeout.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <sys/select.h>
#include <time.h>
#include <signal.h>
struct termios saved_tattr;
int run = 1;
void
sighandler(int sig)
{
(void)sig;
run = 0;
}
void
restore_tattr (void)
{
if (isatty (STDIN_FILENO))
tcsetattr (STDIN_FILENO, TCSANOW, &saved_tattr);
printf ("\033[?1006l\033[?1004l\033[?1000l");
exit(0);
}
int
ready_select ()
{
struct timeval timeoutstru;
fd_set readfds;
int nfds;
timeoutstru.tv_sec = 0;
timeoutstru.tv_usec = 800000;
FD_ZERO (& readfds);
FD_SET (STDIN_FILENO, & readfds);
nfds = select (STDIN_FILENO + 1, & readfds, 0, 0, & timeoutstru);
printf ("(%d)", nfds);
return nfds;
}
int
main (void)
{
signal(SIGINT, sighandler);
if (isatty (STDIN_FILENO)) {
struct termios tattr;
tcgetattr (STDIN_FILENO, &saved_tattr);
tattr = saved_tattr;
/*
tattr.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
tattr.c_oflag &= ~OPOST;
tattr.c_cflag &= ~(CSIZE|PARENB);
tattr.c_cflag |= CS8;
tattr.c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
*/
/* use miminal change for test case: */
tattr.c_lflag &= ~(ECHO|ICANON);
tcsetattr (STDIN_FILENO, TCSAFLUSH, &tattr);
atexit (restore_tattr);
}
setbuf (stdout, 0);
printf ("\033[?1000h\033[?1006h\033[?1004h");
while (run) {
unsigned char c;
int res;
while (! ready_select ()) {
}
res = read (STDIN_FILENO, & c, 1);
if (res < 0) break;
switch (c & 0xFF) {
case 0x00 ... 0x1f: putchar ('^'); putchar (c + 0x40);
if (c == '\r') printf ("\r\n");
break;
case 0x7f: putchar ('^'); putchar ('?'); break;
case 0x80 ... 0xFF: printf ("\\x%2X", c); break;
default: putchar (c);
}
fflush (stdout);
}
printf ("\033[?1000l\033[?1004l\r\nbye\r\n");
return 0;
}