Direct IO 是一種繞過作業系統頁面快取(Page Cache)、讓資料在使用者緩衝區與裝置之間直接傳輸的機制。對於需要自行掌控快取行為、或處理大量資料的應用場景而言,它能有效降低記憶體複製帶來的額外開銷。
要在程式中啟用 Direct IO,主要需要完成以下三件事:
(1)宣告必要的巨集。在引用標頭檔之前,先定義 #define _USE_GNU 1 與 #define _GNU_SOURCE,才能取得相關的 POSIX 介面。
(2)開啟檔案時加上 O_DIRECT 旗標。例如:
int writefd = open(dev, O_RDWR | O_DIRECT);
(3)讓資料緩衝區與頁對齊。讀寫用的 buf 必須對齊到系統頁面大小,同時偏移位址也必須是頁面大小的整數倍,否則讀寫會失敗。
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#define _USE_GNU 1
#define _GNU_SOURCE
int main()
{
char *buf;
size_t buf_size = 1024;
off_t offset = 4096;
// 讓 buf 與頁面對齊
posix_memalign((void **)&buf, getpagesize(), buf_size);
int writefd = open("a.txt", O_RDWR | O_DIRECT);
if (writefd < 0)
{
printf("can't open the file!\n");
exit(1);
}
// 偏移位址必須是頁面大小的整數倍
if (lseek(writefd, offset, SEEK_SET) < 0)
{
printf("lseek the disk is error!\n");
exit(1);
}
if (buf_size != (size_t)read(writefd, buf, buf_size))
{
perror("read data from the disk is error!");
exit(1);
}
close(writefd);
free(buf);
return 0;
}
(1)buf 務必使用 posix_memalign() 進行頁面對齊,一般的 malloc() 無法保證對齊。
(2)lseek 的偏移位址必須是頁面大小的整數倍。