C 跟踪 aio_read 任务

标签 c aio

我有一个启动 aio_read 任务并返回主程序的函数。

我想定期检查任务是否完成以关闭文件描述符并可能通知用户。

我当前的方法是声明一个 struct,其中包含任务的 struct aiocb 和文件描述符。将其添加到全局数组并检查是否有任何任务正在使用以下(aio_check 函数):

#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <aio.h>
#include <unistd.h>

#include "aioqueue.h"

void aio_add(struct aiocb a, int fd) {
    for (int i = 0; i < MAX; i++) {
        if (aio_array[i].valid == 0) {
            aio_pack tmp;
            tmp.cb = a;
            tmp.fd = fd;
            tmp.valid = 1;
            aio_array[i] = tmp;

            printf("request enqueued\n");
            return;
        }
    }
    printf("This shell cannot keep track of so many IO operations :/ \n");
}

void aio_check() {
    for (int i = 0; i < MAX; i++) {
        // wait until the request has finished
        if(aio_array[i].valid) {
            if (aio_error(&aio_array[i].cb) != EINPROGRESS) {
                int nleidos = aio_return(&aio_array[i].cb);

                if (nleidos != -1)
                    printf("AIO Task finished: %d B\n", nleidos);
                else
                    printf("Error!");

                close(aio_array[i].fd); 
                aio_array[i].valid = 0; 
            } else {
                printf("At least one AIO task is in progress\n");           
            }
        }
    }
}

和aioqueue.h的代码

#define MAX 10

typedef struct {
    struct aiocb cb;
    int fd;
    int valid;
} aio_pack;

aio_pack aio_array[MAX];

void aio_add(struct aiocb a, int fd);
void aio_check();

问题是,如果我在添加任务后调用 aio_check,我总是会得到

At least one AIO task is in progress

消息。即使很明显任务已经完成。

我想这可能是因为我在 aio_errorEINPROGRESS 的时刻传递了 struct aiocb 的副本> 作为副本,它永远不会更新。但此刻我很迷茫。任何帮助将不胜感激。

提前谢谢你。

最佳答案

您需要调用 aio_suspend() 来处理已完成的 I/O,否则 aio_error() 等将永远不会返回不同的结果。参见 https://github.com/ned14/llfio/blob/master/include/llfio/v2.0/detail/impl/posix/io_service.ipp#L290 .

关于C 跟踪 aio_read 任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53510586/

相关文章:

c - 我怎样才能用c语言声明一个文件名?

无法理解输出

linux - 使用内核 AIO 的应用程序

macos - osx 上的 aio : Is it implemented in the kernel or with user threads? 其他选项?

c - 如何 #define 一个函数来替换另一个函数?

c - 用C读取带有空格的文件.txt

c - C中的字数统计,学习更多CS

c - `open`和 `close`如何异步串口?

posix - 重新访问 "how do you use aio and epoll together"

linux - POSIX AIO 库和回调处理程序