Direct IO的程式實現

來源:互聯網
上載者:User

實現Direct IO的程式實現

(1)首先要在應用前加上宏:#define _USE_GNU 1 和#define _GNU_SOURCE

(2)在open一個裝置檔案的時候要加上O_DERECT選項。如: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(fd,offset,SEEK_SET)<0)

              //if(lseek(fd,0,SEEK_SET)<0)

              {

                     printf("lseekthe disk is error!\n");

                     exit(1);           }             

   if(buf_size!= read(fd,buf,buf_size))

              {

                     perror("readdata from the disk is error!");

                        printf("thetem_size is %d\n",temp_size);

                     exit(1);

              }

}

注意以下幾點:(1)buf必須要用函數posix_memalign()來與頁進行對齊。

            (2)lseek的位移地址必須是頁面大小的整數倍。

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.