我是异步 I/O 的新手。我需要让它在 Linux 系统上的一些 C 和 Fortran 程序中工作。我设法编写了一个从两个文件异步读取的小 C 测试代码(包括在下面)。代码编译并运行。不过,我想知道的是,我是真正获得异步 I/O,还是 I/O 真的是串行的?我正在处理的 luster 文件系统有点过时,不清楚它是否真正支持异步 I/O,似乎没有人有明确的答案。所以我想知道是否有一些时间语句或任何类型的输出可以添加到代码中,以确定它是否以真正异步的方式运行。我打赌我需要比我正在处理的文件大得多的文件才能进行有意义的测试。不知道我还需要什么。
代码是:
#include <stdio.h>
#include <stdlib.h>
/* for "open()" ... */
#include <fcntl.h>
/* for "bzero()" ... */
#include<strings.h>
/* for asynch I/O ... */
#include <aio.h>
/* for EINPROGRESS ... */
#include <errno.h>
/* for "usleep()" ... */
#include <unistd.h>
#define BUFSIZE 1024
int main() {
int fd0, fd1, readstat0, readstat1;
struct aiocb *ioobjs[2];
ioobjs[0] = malloc(sizeof(struct aiocb));
ioobjs[1] = malloc(sizeof(struct aiocb));
fd0 = open("file.txt", O_RDONLY);
if (fd0 < 0) perror("open");
fd1 = open("otherfile.txt", O_RDONLY);
if (fd1 < 0) perror("open");
bzero((char *)ioobjs[0], sizeof(struct aiocb));
bzero((char *)ioobjs[1], sizeof(struct aiocb));
ioobjs[0]->aio_buf = malloc(BUFSIZE+1);
if (!ioobjs[0]->aio_buf) perror("malloc 0");
ioobjs[1]->aio_buf = malloc(BUFSIZE+1);
if (!ioobjs[1]->aio_buf) perror("malloc 0");
ioobjs[0]->aio_fildes = fd0;
ioobjs[0]->aio_nbytes = BUFSIZE;
ioobjs[0]->aio_offset = 0;
/* Don't forget this! With list I/O, there is no
* particular function call to make. You have to
* tell what you want to do via this member of
* your aiocb struct:
*/
ioobjs[0]->aio_lio_opcode = LIO_READ;
ioobjs[1]->aio_fildes = fd1;
ioobjs[1]->aio_nbytes = BUFSIZE;
ioobjs[1]->aio_offset = 0;
ioobjs[1]->aio_lio_opcode = LIO_READ;
readstat0 = aio_read(ioobjs[0]);
if (readstat0 < 0) perror("reading 0");
readstat1 = aio_read(ioobjs[1]);
if (readstat1 < 0) perror("reading 1");
lio_listio(LIO_NOWAIT, ioobjs, 2, NULL);
/* don't completely understand. gives system time to
* "wrap things up". without this, one of the outputs
* below (maybe both) will have no output to give.
*/
usleep(100);
if ((readstat0 = aio_return( ioobjs[0] )) > 0) {
printf(">>>\n");
printf("%s\n", (char *)(ioobjs[0]->aio_buf));
printf("<<<\n");
} else {
perror("return");
}
if ((readstat1 = aio_return( ioobjs[1] )) > 0) {
printf(">>>\n");
printf("%s\n", (char *)(ioobjs[1]->aio_buf));
printf("<<<\n");
} else {
perror("return");
}
}