日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 综合教程 >内容正文

综合教程

Linux下libaio的一个简单例子

發布時間:2024/8/26 综合教程 31 生活家
生活随笔 收集整理的這篇文章主要介紹了 Linux下libaio的一个简单例子 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

libaio是Linux下的一個異步非阻塞接口,它提供了以異步非阻塞方式來讀寫文件的方式,讀寫效率比較高。

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

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

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

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

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

 1 #include<stdio.h>
2 #include<fcntl.h>
3 #include<string.h>
4 #include<stdlib.h>
5 #include<libaio.h>
6 #include<errno.h>
7 #include<unistd.h>
8 int main(void){
9 int output_fd;
10 const char *content="hello world!";
11 const char *outputfile="hello.txt";
12 io_context_t ctx;
13 struct iocb io,*p=&io;
14 struct io_event e;
15 struct timespec timeout;
16 memset(&ctx,0,sizeof(ctx));
17 if(io_setup(10,&ctx)!=0){//init
18 printf("io_setup error\n");
19 return -1;
20 }
21 if((output_fd=open(outputfile,O_CREAT|O_WRONLY,0644))<0){
22 perror("open error");
23 io_destroy(ctx);
24 return -1;
25 }
26 io_prep_pwrite(&io,output_fd,content,strlen(content),0);
27 io.data=content;
28 if(io_submit(ctx,1,&p)!=1){
29 io_destroy(ctx);
30 printf("io_submit error\n");
31 return -1;
32 }
33 while(1){
34 timeout.tv_sec=0;
35 timeout.tv_nsec=500000000;//0.5s
36 if(io_getevents(ctx,0,1,&e,&timeout)==1){
37 close(output_fd);
38 break;
39 }
40 printf("haven't done\n");
41 sleep(1);
42 }
43 io_destroy(ctx);
44 return 0;
45 }

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

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

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

總結

以上是生活随笔為你收集整理的Linux下libaio的一个简单例子的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。