Skip to content

Instantly share code, notes, and snippets.

@ayosec
Created April 18, 2021 23:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ayosec/4f9be61d370b3cf9c623b85513ce9fbb to your computer and use it in GitHub Desktop.
Save ayosec/4f9be61d370b3cf9c623b85513ce9fbb to your computer and use it in GitHub Desktop.
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
struct termios initial_term_params;
// Check if both stdin and stdout are TTYs.
void check_stdio() {
if(isatty(STDIN_FILENO) != 1 || isatty(STDOUT_FILENO) != 1) {
perror("stdio");
exit(1);
}
}
// Restore terminal parameters at exit.
void reset_term_params() {
tcsetattr(STDIN_FILENO, TCSAFLUSH, &initial_term_params);
}
// Disable echo and canonical mode.
void init_tty() {
struct termios term_params;
// Get terminal parameters to reset them at exit,
if (tcgetattr(STDOUT_FILENO, &term_params) == -1) {
perror("tcgetattr");
exit(1);
}
// Store initial parameters to restore them.
initial_term_params = term_params;
term_params.c_lflag &= ~(ICANON|ECHO);
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &term_params) == -1) {
perror("tcsetattr");
exit(1);
}
atexit(reset_term_params);
}
// Send XTSMGRAPHICS and DA1.
void send_query() {
printf("\033[?1;1;0S\033[c");
fflush(stdout);
}
// Read response in stdin.
//
// A real program should parse the read data. We are just printing it.
void read_response() {
char c;
int timeout;
int esc_count;
struct pollfd pollfd = { .fd = 0, .events = POLLIN };
timeout = 5000;
esc_count = 0;
while(poll(&pollfd, 1, timeout) == 1) {
read(0, &c, 1);
if(c == 0x1B) {
esc_count++;
if(esc_count > 1)
putc('\n', stdout);
}
if(c < ' ')
printf("\\x%X", (int)c);
else
putc(c, stdout);
// Don't wait after first char is read.
timeout = 0;
}
putc('\n', stdout);
}
int main() {
check_stdio();
init_tty();
send_query();
read_response();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment