forked from majnemer/davesdots
-
Notifications
You must be signed in to change notification settings - Fork 0
/
answerback.c
102 lines (85 loc) · 1.75 KB
/
answerback.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
92
93
94
95
96
97
98
99
100
101
102
#define _POSIX_C_SOURCE 200112L
#include <signal.h> /* for signal handling */
#include <stdio.h> /* fopen(), et al. */
#include <fcntl.h> /* for open() */
#include <unistd.h> /* for ssize_t, read(), write() */
#include <stdlib.h> /* for EXIT_SUCCESS, EXIT_FAILURE */
#include <termios.h> /* ctermid(), et al. */
#define ANSWERBACK_LEN 16
#define ANSWERBACK_CODE 5
static struct termios old_term;
static int fd;
static void
tty_reset(void)
{
if (tcsetattr(fd, TCSAFLUSH, &old_term) == -1)
{
perror("tcsetattr");
}
if (close(fd) == -1)
{
perror("close");
}
}
int main()
{
char term[L_ctermid];
const char *cterm = ctermid(term);
if (cterm[0] == '\0')
{
(void)fputs("Cannot get the path to the console", stderr);
return EXIT_FAILURE;
}
if ((fd = open(cterm, O_RDWR)) == -1)
{
perror("open");
return EXIT_FAILURE;
}
if (tcgetattr(fd, &old_term) == -1)
{
perror("tcgetattr");
return EXIT_FAILURE;
}
if (atexit(tty_reset) != 0)
{
(void)fputs("Cannot set the exit function", stderr);
return EXIT_FAILURE;
}
struct termios new_term = old_term;
new_term.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL | ICANON | ISIG | IEXTEN);
new_term.c_cc[VMIN] = 0;
new_term.c_cc[VTIME] = 1;
if (tcsetattr(fd, TCSAFLUSH, &new_term) == -1)
{
perror("tcsetattr");
return EXIT_FAILURE;
}
char code = ANSWERBACK_CODE;
for (;;)
{
ssize_t ret = write(fd, &code, sizeof(code));
if (ret == -1)
{
perror("write");
return EXIT_FAILURE;
}
else if (ret > 0)
{
break;
}
}
char buffer[ANSWERBACK_LEN] = { 0 };
ssize_t ret = read(fd, buffer, sizeof(buffer) - 1);
if (ret == -1)
{
perror("read");
return EXIT_FAILURE;
}
buffer[ret] = '\0';
if (ret == 0)
{
return EXIT_FAILURE;
}
puts(buffer);
return EXIT_SUCCESS;
}