dots/answerback.c

102 lines
1.7 KiB
C
Raw Normal View History

#define _POSIX_C_SOURCE 200112L
2010-10-28 02:25:47 -05:00
#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. */
2010-10-28 01:38:30 -05:00
#define ANSWERBACK_LEN 16
#define ANSWERBACK_CODE 5
2010-10-28 02:25:47 -05:00
static struct termios old_term;
static int fd;
2010-10-28 02:25:47 -05:00
static void
tty_reset(void)
{
if (tcsetattr(fd, TCSAFLUSH, &old_term) == -1)
{
2010-10-28 02:25:47 -05:00
perror("tcsetattr");
}
2010-10-28 02:25:47 -05:00
if (close(fd) == -1)
{
2010-10-28 02:25:47 -05:00
perror("close");
2010-10-28 01:38:30 -05:00
}
2010-10-28 02:25:47 -05:00
}
2010-10-28 01:38:30 -05:00
2010-10-28 02:25:47 -05:00
int main()
{
const char *cterm = ctermid(NULL);
2010-10-28 02:25:47 -05:00
if (cterm == NULL)
{
2010-10-28 02:25:47 -05:00
fputs("Cannot get the path to the console", stderr);
return EXIT_FAILURE;
}
2010-10-28 02:25:47 -05:00
if ((fd = open(cterm, O_RDWR)) == -1)
{
2010-10-28 02:25:47 -05:00
perror("open");
return EXIT_FAILURE;
}
2010-10-28 02:25:47 -05:00
if (tcgetattr(fd, &old_term) == -1)
{
2010-10-28 02:25:47 -05:00
perror("tcgetattr");
return EXIT_FAILURE;
}
2010-10-28 02:25:47 -05:00
if (atexit(tty_reset) != 0)
{
2010-10-28 02:25:47 -05:00
fputs("Cannot set the exit function", stderr);
return EXIT_FAILURE;
}
struct termios new_term = old_term;
2010-10-28 02:25:47 -05:00
new_term.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL | ICANON | ISIG | IEXTEN);
new_term.c_cc[VMIN] = 0;
2010-10-27 15:48:50 -05:00
new_term.c_cc[VTIME] = 1;
if (tcsetattr(fd, TCSAFLUSH, &new_term) == -1)
{
perror("tcsetattr");
return EXIT_FAILURE;
}
2010-10-28 01:38:30 -05:00
char code = ANSWERBACK_CODE;
for (;;)
{
2010-10-28 01:38:30 -05:00
ssize_t ret = write(fd, &code, sizeof(code));
if (ret == -1)
{
perror("write");
return EXIT_FAILURE;
}
else if (ret > 0)
{
break;
}
}
2010-10-28 01:38:30 -05:00
char buffer[ANSWERBACK_LEN] = { 0 };
ssize_t ret = read(fd, buffer, sizeof(buffer) - 1);
if (ret == -1)
{
perror("read");
return EXIT_FAILURE;
}
2010-10-28 02:25:47 -05:00
buffer[ret] = '\0';
2010-10-28 01:38:30 -05:00
if (ret == 0)
{
2010-10-28 01:38:30 -05:00
return EXIT_FAILURE;
}
2010-10-28 01:38:30 -05:00
puts(buffer);
return EXIT_SUCCESS;
}