AIO读操作,使用系统调用实现
#define BUFSIZE 1024
#include <stdio.h>
#include <stdlib.h>
#include <aio.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
int main(void) {
int fd, ret;
struct aiocb my_aiocb;
fd = open("file.txt", O_RDONLY);
if (fd < 0)
perror("open");
/* Zero out the aiocb structure (recommended) */
bzero((char *) &my_aiocb, sizeof(struct aiocb));
/* Allocate a data buffer for the aiocb request */
my_aiocb.aio_buf = malloc(BUFSIZE + 1);
if (!my_aiocb.aio_buf)
perror("malloc");
/* Initialize the necessary fields in the aiocb */
my_aiocb.aio_fildes = fd;
my_aiocb.aio_nbytes = BUFSIZE;
my_aiocb.aio_offset = 0;
ret = aio_read(&my_aiocb);
if (ret < 0)
perror("aio_read");
/**
aio_error return value :
EINPROGRESS,说明请求尚未完成
ECANCELLED,说明请求被应用程序取消了
-1,说明发生了错误,具体错误原因可以查阅 errno.h
*/
while (aio_error(&my_aiocb) == EINPROGRESS)
;
if ((ret = aio_return(&my_aiocb)) > 0) {
/* got ret bytes on the read */
int n = my_aiocb.aio_nbytes; //length
char *p0=(char *)my_aiocb.aio_buf; //返回字符
printf("p0 is %s\n",p0);
puts("!read success!!!");
printf("buffersize is %d,real byte size is %d", n, ret);
} else {
/* read failed, consult errno */
puts("!!!read fail!!");
}
return 0;
}
这样建立一个测试文件,就可以异步读取了,使用gcc编译的时候注意链接动态库librt编译命令如下:
gcc -o myaio myaio.c /lib/librt.so.1
librt.so.1为我的rt动态链接库,在/lib目录下