Search code examples
cioansi-escape

How do write() and read() interact in C (<unistd.h>)?


I am having trouble understanding how read() and write() work in C. The code that I am working with seems to be writing to STDOUT_FILENO and reading in the same data from STDIN_FILENO. I am wondering if that's supposed to be the case or not, since the two file descriptors are different.

I've already looked at the man pages and they didn't seem to help at all.

Here's the code:

if (write(STDOUT_FILENO, "\x1b[6n", 4) != 4) return -1;
printf("\r\n");
char c;
while (read(STDIN_FILENO, &c, 1) == 1) {
  if (iscntrl(c)) {
    printf("%d\r\n", c);
  } else {
    printf("%d ('%c')\r\n", c, c);
  }
}

The code outputs the escape sequence that were written out in the way the if statment formats it, which meant that the STDIN_FILENO somehow read the output of the STDOUT_FILENO. Is that how it's supposed to work, and if so, why?


Solution

  • No, it does exactly what you ask for:

    ^[[6n is the ansi escape sequence for DSR (device status report). This reports the current position of your cursor to your terminal input (stdin) in the format ^[[r;cR with "r" and "c" being "row" and "column". You can use this to determine the cursor location in your terminal.

    This is a special feature of the terminal, which understands and processes such control codes, and is not the usual behaviour of stdin/stdout. Usually, you do not read from stdin what you wrote to stdout (it is also not the case here, it only looks similar!)