谷歌搜索“Linux async io”提供了一些关于 AIO 功能的信息
非常神秘。
这是一个例子。
// Link with '-lrt'.
#define _FILE_OFFSET_BITS 64
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <aio.h>
#define BUFSIZE 0x100000 // 1 MiB
int xopen(const char *path)
{
int fd = open(path, O_RDONLY|O_DIRECT);
if (fd < 0) perror(path), exit(EXIT_FAILURE);
return fd;
}
void *xalloc()
{
void *mem = memalign(0x1000, BUFSIZE);
if (!mem) perror("memalign"), exit(EXIT_FAILURE);
return mem;
}
void xread(struct aiocb *cbp)
{
if (aio_read(cbp) < 0) perror("aio_read"), exit(EXIT_FAILURE);
}
size_t xwait(struct aiocb *cbp)
{
if (aio_suspend((const struct aiocb **)&cbp, 1, NULL) < 0)
perror("aio_suspend"), exit(EXIT_FAILURE);
if (aio_error(cbp)) perror("aio_error"), exit(EXIT_FAILURE);
ssize_t n = aio_return(cbp);
if (n < 0) perror("aio_return"), exit(EXIT_FAILURE);
cbp->aio_offset += n; // prepare for next read
return n;
}
size_t min(size_t a, size_t b) { return a < b ? a : b; }
main()
{
int lt = 0, gt = 0, eq = 0; // counters for chunks A less, greater, equal B
int fd[2] = { xopen("/dev/sda"), xopen("/dev/sdb") };
// 2 buffer pairs: one for reading data, other holding previously read data
char *buf[2][2] = { xalloc(), xalloc(), xalloc(), xalloc() };
_Bool flp = 0; // flag which buffer pair to use for reading data
struct aiocb cb[2] =
{ { .aio_fildes = fd[0], .aio_nbytes = BUFSIZE },
{ .aio_fildes = fd[1], .aio_nbytes = BUFSIZE }
};
size_t n = 0;
do
{
cb[0].aio_buf = buf[0][flp], cb[1].aio_buf = buf[1][flp], flp = !flp;
xread(&cb[0]), xread(&cb[1]);
if (n) // Do we have previously read data to work on?
{
int s = memcmp(buf[0][flp], buf[1][flp], n);
if (s < 0) ++lt; else if (s > 0) ++gt; else ++eq;
}
} while (n = min(xwait(&cb[0]), xwait(&cb[1])));
close(fd[0]), close(fd[1]);
if (eq) printf("%7d chunks of A equal to B\n", eq);
if (lt) printf("%7d chunks of A less than B\n", lt);
if (gt) printf("%7d chunks of A greater than B\n", gt);
return 0;
}