您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

Linux 開發實戰:Direct I/O 的程式實現

編輯:iOS 開發綜合

Direct I/O 是一種繞過作業系統頁面快取、直接在使用者空間與裝置之間進行資料傳輸的機制。本文整理在程式中啟用 Direct I/O 的三個關鍵步驟與範例程式。

一、三個關鍵步驟

  1. 在程式開頭加上巨集定義:#define _USE_GNU 1 與 #define _GNU_SOURCE。
  2. 開啟裝置檔案時加上 O_DIRECT 選項,例如:int writefd = open(dev, O_RDWR | O_DIRECT);
  3. 把要讀寫的 buf 與頁對齊,同時確保偏移位址是頁大小的整數倍。

二、範例程式

#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);
    }
}

三、注意事項

  1. buf 必須使用 posix_memalign() 函數來與記憶體頁對齊。
  2. lseek 的偏移位址必須是頁面大小的整數倍。

只要嚴格遵守對齊與偏移的規則,就能正確使用 Direct I/O 來達成繞過快取的直接存取。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved