简体   繁体   English

C 中的 write() 和 read() 如何交互(<unistd.h> )?

[英]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 .我无法理解read()write()在 C 中的工作方式。我正在使用的代码似乎正在写入STDOUT_FILENO并从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 .该代码输出一个是在路上写出来的转义序列if statment进行格式化,这意味着该STDIN_FILENO莫名其妙读取的输出STDOUT_FILENO Is that how it's supposed to work, and if so, why?这是它应该如何工作的,如果是这样,为什么?

No, it does exactly what you ask for:不,它完全符合您的要求:

^[[6n is the ansi escape sequence for DSR (device status report). ^[[6n是 DSR(设备状态报告)的 ansi 转义序列。 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".这会将光标的当前位置以 ^[[r;cR 格式报告给终端输入 (stdin),其中“r”和“c”是“行”和“列”。 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.这是terminal 的一个特殊功能,它理解并处理这样的控制代码,而不是 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!)通常,您不会从 stdin 读取您写入 stdout 的内容(这里也不是这种情况,它只是看起来相似!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM