I had a look into escape codes and found some C code that reads the current cursor position. And I guess I have now stumbled over a topic of UNIX/POSIX programming I until now had not much exposure to.
The below code opens dev/tty
in read-write mode and writes the appropriate escape code to the file-descriptor, then receives the answer by reading from the file-descriptor. so programmatically I understand whats going on.
Conceptionally I wonder
- Why is the TTY device opened (as opposed to stdin/stdout usage)
- If I open a TTY device, wouldn't I have to first find out the current tty (by opening a pipe to
/usr/bin/tty
for example, then opening this device).
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(void) {
int tty_fd = open("/dev/tty", O_RDWR);
if (tty_fd < 0) {
printf("Cannot open /devv/tty: errno = %d, %s\r\n", errno, strerror(errno));
exit(EXIT_FAILURE);
}
write(tty_fd, "\x1B[6n\n", 5);
unsigned char res[16] = {0};
size_t j = 0;
for (j = 0; j < sizeof(res) - 1 && read(tty_fd, res + j, 1) == 1; j++) {
printf("%d\n", res[j]);
if (res[j] == 'R') {
break;
res[j] = '\0';
}
}
printf("Answerback = %s", res + 1);
return 0;
}
/dev/tty
is the current terminal, if one is attached at all. As I can only do hand-waving with regards to this topic, I won't convert this into an answer.