linux系统scatter/gather I/O技术

struct iovec 是一种用于分散/聚集 I/O 操作的数据结构,它允许在一次系统调用中从多个非连续内存缓冲区读取或写入多个非连续内存缓冲区。

该结构通常与 readv 和 writev 等函数一起使用。

#include <sys/uio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
int main() {
   // Buffers for scatter/gather I/O
   char buf1[10], buf2[20];
   struct iovec iov[2];
   // Initialize iovec structures
   iov[0].iov_base = buf1;
   iov[0].iov_len = sizeof(buf1);
   iov[1].iov_base = buf2;
   iov[1].iov_len = sizeof(buf2);
   // Open a file
   int fd = open("example.txt", O_RDONLY);
   if (fd == -1) {
       perror("open");
       return 1;
   }
   // Perform scatter read
   ssize_t bytesRead = readv(fd, iov, 2);
   if (bytesRead == -1) {
       perror("readv");
       close(fd);
       return 1;
   }
   printf("Read %zd bytes\n", bytesRead);
   printf("Buffer 1: %.*s\n", (int)iov[0].iov_len, buf1);
   printf("Buffer 2: %.*s\n", (int)iov[1].iov_len, buf2);
   close(fd);
   return 0;
}

 

posted @ 2025-10-16 19:00  PKICA  阅读(17)  评论(0)    收藏  举报