Linux下libaio的一个简单例子

本文介绍了Linux下的异步非阻塞接口libaio,通过一个简单的示例程序展示了如何使用libaio进行文件的非阻塞读写操作。libaio允许用户在发出读写请求后继续执行其他任务,当读写完成后会收到通知。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

转载于:https://www.cnblogs.com/aLittleBitCool/archive/2011/10/18/2216646.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值