libaio介绍
The Linux-native asynchronous I/O facility ("async I/O", or "aio") has a richer API and capability set than the simple POSIX async I/O facility. This library, libaio, provides the Linux-native API for async I/O. The POSIX async I/O facility requires this library in order to provide kernel-accelerated async I/O capabilities, as do applications which require the Linux-native async I/O API.
libaio项目 Overview - libaio - Pagure.iohttps://pagure.io/libaio
centos下安装libaio库
# sudo yum install libaio-devel
libaio提供四个函数如下表:
函数 | 功能 | 原型 |
io_setup | 创建一个异步IO上下文(io_context_t是一个句柄) | int io_setup(int maxevents, io_context_t *ctxp); |
io_destroy | 销毁一个异步IO上下文(如果有正在进行的异步IO,取消并等待它们完成) | int io_destroy(io_context_t ctx); |
io_submit | 提交异步IO请求 | long io_submit(aio_context_t ctx_id, long nr, struct iocb **iocbpp); |
io_cancel | 取消一个异步IO请求 | long io_cancel(aio_context_t ctx_id, struct iocb *iocb, struct io_event *result); |
io_getevents | 等待并获取异步IO请求的事件(也就是异步请求的处理结果) | long io_getevents(aio_context_t ctx_id, long min_nr, long nr, struct io_event *events, struct timespec *timeout); |
五个宏定义:
void io_set_callback(struct iocb *iocb, io_callback_t cb);
void io_prep_pwrite(struct iocb *iocb, int fd, void *buf, size_t count, long long offset);
void io_prep_pread(struct iocb *iocb, int fd, void *buf, size_t count, long long offset);
void io_prep_pwritev(struct iocb *iocb, int fd, const struct iovec *iov, int iovcnt, long long offset);
void io_prep_preadv(struct iocb *iocb, int fd, const struct iovec *iov, int iovcnt, long long offset);
这五个宏定义都是操作struct iocb的结构体。struct iocb是libaio中很重要的一个结构体,用于表示IO,但是其结构略显复杂,为了保持封装性不建议直接操作其元素而用上面五个宏定义操作。
测试
测试源代码 test.c
#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;
char *content="hello world!";
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;
}
Makefile:
test:
gcc test.c -o test -laio
clean:
rm -rf test
其他参考文档:
Linux Asynchronous I/O (oxnz.github.io)https://oxnz.github.io/2016/10/13/linux-aio/