-
Notifications
You must be signed in to change notification settings - Fork 0
/
tst.c
75 lines (62 loc) · 1.24 KB
/
tst.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
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>
#define BUFLEN 40
time_t start_time;
void cleanup(void);
void toggle_term_mode(int term);
/* COMMANDS */
void write_time(void)
{
time_t run_length;
char buf[BUFLEN];
printf("\033[2K\r"); /* clear line */
run_length = time(NULL) - start_time;
strftime(buf, BUFLEN, "%H:%M:%S", gmtime(&run_length));
printf("%s", buf);
}
/* INIT */
void cleanup(void)
{
toggle_term_mode(0);
}
/* when term is 1, turn off canonical mode. turn on when 0 */
void toggle_term_mode(int term)
{
static struct termios orig, new;
if (term == 1) {
/* turn off icanon */
tcgetattr(STDIN_FILENO, &orig);
new = orig;
new.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &new);
} else {
/* turn on icanon */
tcsetattr(STDIN_FILENO, TCSANOW, &orig);
}
}
int main(int argc, char **argv)
{
atexit(cleanup);
toggle_term_mode(1);
int c;
printf("h\n\n");
start_time = time(NULL);
while ((c = getchar()) != EOF && c != 3) { /* the second one is C-c */
switch (c) {
case ' ':
write_time();
break;
case '\n':
printf("\n");
break;
case 'q':
ungetc(3, stdin); /* bodge solution */
break;
}
}
printf("\n");
return 0;
}