0

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

  1. Why is the TTY device opened (as opposed to stdin/stdout usage)
  2. 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;
}
1
  • The standard streams aren't always connected to a terminal, and /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.
    – Kusalananda
    Commented Jun 12, 2022 at 20:14

1 Answer 1

1
  1. Opening and using /dev/tty ensures that the process has a controlling terminal, and that that’s where the escape codes actually go. Writing to standard output and reading from standard input is subject to whatever redirections are in place, if any.

    In fact, running the example program with its output redirected to a file will result in the output going to the file, but the cursor position being read from the terminal (if there is one).

  2. /dev/tty is always the current process’ controlling terminal, if it has one. See what relations are between my current controlling terminal and `/dev/tty`? for details. There’s no need for a level of indirection here, /dev/tty provides that itself.

1
  • Thanks a lot, that clarifies a lot!
    – wirrbel
    Commented Jun 13, 2022 at 6:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .