基本步骤
- 包含头文件:需要包含
<aio.h>
头文件,以使用异步I/O相关函数。
- 初始化
struct aiocb
结构体:该结构体用于描述异步I/O操作,需要填充文件描述符(通过open
等函数获取)、缓冲区指针、写入字节数等信息。
- 调用
aio_write
函数:传入初始化好的struct aiocb
结构体指针来启动异步写入操作。
- 检查操作状态:可以通过
aio_error
函数检查异步操作是否完成,若完成可使用aio_return
获取返回值。
示例代码
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <aio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#define BUFFER_SIZE 1024
int main() {
int fd;
struct aiocb my_aiocb;
// 打开文件
fd = open("test.txt", O_WRONLY | O_CREAT, 0644);
if (fd == -1) {
perror("open");
return EXIT_FAILURE;
}
// 初始化aiocb结构体
memset(&my_aiocb, 0, sizeof(struct aiocb));
my_aiocb.aio_fildes = fd;
my_aiocb.aio_buf = "Hello, asynchronous I/O!";
my_aiocb.aio_nbytes = strlen((char *)my_aiocb.aio_buf);
my_aiocb.aio_offset = 0;
// 发起异步写入操作
if (aio_write(&my_aiocb) == -1) {
perror("aio_write");
close(fd);
return EXIT_FAILURE;
}
// 检查操作状态
int error;
while ((error = aio_error(&my_aiocb)) == EINPROGRESS) {
// 操作仍在进行,可在此处执行其他任务
sleep(1);
}
if (error != 0) {
errno = error;
perror("aio_error");
} else {
ssize_t ret = aio_return(&my_aiocb);
if (ret == -1) {
perror("aio_return");
} else {
printf("成功写入 %zd 字节\n", ret);
}
}
// 关闭文件
close(fd);
return EXIT_SUCCESS;
}