Linux下libaio的一個簡單例子

來源:互聯網
上載者:User

標籤:

轉載:http://www.cnblogs.com/aLittleBitCool/archive/2011/10/18/2216646.html

非同步io,很好玩的一個東西,從介面來看,封裝的比較厲害,有時間研究內部實現,可以在項目中考慮替代select.

libaio是Linux下的一個非同步非阻塞介面,它提供了以非同步非阻塞方式來讀寫檔案的方式,讀寫效率比較高。

首先推薦兩個介紹Linux I/O模型的頁面,寫的很好:

http://www.ibm.com/developerworks/cn/linux/l-async/

http://www.iteye.com/topic/868702

對於libaio的讀寫過程簡單說來就是你發出一個讀寫請求,然後你可以開始做其他事情,當讀寫過程結束時libaio會通知你你的這次請求已經完成(而select模型是告訴你讀寫已經就緒)。

這裡給出一個很簡單的小例子,具體函數可以通過man查看:

#include<stdio.h>#include<fcntl.h>#include<string.h>#include<stdlib.h>#include<libaio.h>#include<errno.h>#include<unistd.h>int main(void){    int output_fd;    const char *content="hello world!";    const char *outputfile="hello.txt";    io_context_t ctx;    struct iocb io,*p=&io;    struct io_event e;    struct timespec timeout;    memset(&ctx,0,sizeof(ctx));     if(io_setup(10,&ctx)!=0){//init        printf("io_setup error\n");         return -1;     }       if((output_fd=open(outputfile,O_CREAT|O_WRONLY,0644))<0){           perror("open error");        io_destroy(ctx);        return -1;     }       io_prep_pwrite(&io,output_fd,content,strlen(content),0);    io.data=content;    if(io_submit(ctx,1,&p)!=1){        io_destroy(ctx);        printf("io_submit error\n");            return -1;     }       while(1){        timeout.tv_sec=0;        timeout.tv_nsec=500000000;//0.5s        if(io_getevents(ctx,0,1,&e,&timeout)==1){               close(output_fd);            break;        }           printf("haven‘t done\n");        sleep(1);    }       io_destroy(ctx);    return 0;}

  

有關libaio更加詳細的內容可以看以下兩個頁面:

http://tiaozhanshu.com/libaio-api.html

http://lse.sourceforge.net/io/aio.html

Linux下libaio的一個簡單例子

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.