• Linux下libaio的一个简单例子


    转载: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
    "); 
            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
    ");    
            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
    ");
            sleep(1);
        }   
        io_destroy(ctx);
        return 0;
    }
    

      

    有关libaio更加详细的内容可以看以下两个页面:

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

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

  • 相关阅读:
    前端调用后台接口下载word文档的两种方法
    Layui form表单提交注意事项
    JavaScript_Util_01
    心理
    小例子
    SQL分割字符串
    绘制10种不同颜色的散点图
    绘制散点图
    subplot的使用
    绘制正弦余弦
  • 原文地址:https://www.cnblogs.com/3me-linux/p/4530245.html
Copyright © 2020-2023  润新知