了解系统级读写功能

Understanding System level read and write functions

本文关键字:功能 读写 系统 了解      更新时间:2023-10-16

由于我对STD iostream和STDIO的不满,我决定创建自己的IO库。这对我的教育很有好处。

但是我有一个小问题。Linux read()在终端文件描述符上操作时,直到新行才会返回。因此,如果我要求10个字节,即使我键入20个字节,也不会返回。更糟糕的是,这10个额外的字节未记录在我通过的缓冲区中。

那10个额外的字节怎么了?Linux是否具有用于读数的缓冲区?我可以访问此缓冲区而不是提供自己的?

因此,Linux终端的默认行为是线条缓冲的。像这样的答案可以适应一次读取一个字符(如果您想要的话)。

要回答有关获取其他10个字节的问题,如果您进行其他阅读,它将返回其余的字节。以下示例演示了多个顺序读取。如果您在提示符处输入10个以上的字符,则第二次读取将在不封锁10和最多返回19个字符的情况下进行。

#include <unistd.h>
#include <stdio.h>
int main(int argc, char** argv)
{
  int read1Count = 0;
  int read2Count = 0;
  char pBuffer[20];
  printf("Provide input: ");
  // flush stdout because buffering...
  fflush(NULL)
  read1Count = read(1, pBuffer, 10);
  // flush stdout because buffering...
  fflush(NULL)
  printf("Provide input: ");
  read2Count = read(1, pBuffer + 10, 10);
  printf("nRead 1: '");
  if (read1Count < 0)
  {
    perror("Error on first read");
  }
  for (int i = 0; i < read1Count; i++)
  {
    printf("%c", pBuffer[i]);
  }
  printf("'nRead 2: '");
  if (read2Count < 0)
  {
    perror("Error on second read");
  }
  for (int i = 0; i< read2Count; i++)
  {
    // We started the second read at pBuffer[10]
    printf("%c", pBuffer[i + 10]);
  }
  printf("'n");
}

编译并运行此内容,我看到了这个

Provide input: 12345678910 Provide input: Read 1: '1234567891' Read 2: '0 '