Direct I/O 是一種繞過作業系統頁面快取、直接在使用者空間與裝置之間進行資料傳輸的機制。本文整理在程式中啟用 Direct I/O 的三個關鍵步驟與範例程式。
#include <stdio.h>
#define _USE_GNU 1
#define _GNU_SOURCE
int main()
{
char *buf;
size_t buf_size = 1024;
off_t offset = 4096;
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 != read(writefd, buf, buf_size))
{
perror("read data from the disk is error!");
exit(1);
}
}
只要嚴格遵守對齊與偏移的規則,就能正確使用 Direct I/O 來達成繞過快取的直接存取。