linux c++:从未调用过 libaio 回调函数?

linux c++: libaio callback function never called?

我在 ubuntu 16.10 上使用 g++ 6.2,测试 libaio 功能:

1. I was trying to test io_set_callback() function
2. I was using main thread and a child thread to talk by a pipe
3. child thread writes periodically (by alarm timer, signal), and main thread reads

我希望使用"callback"功能来接收通知。它没有按预期工作:回调函数 "read_done" 从未被调用

我的问题:

1. I expected my program should call "read_done" function, but actually not.
2. Why the output prints 2 "Enter while" each time? 
I hope it only print together with "thread write msg:..."
3. I tried to comment out "io_getevents" line, same result.

不知道回调模式是否还需要io_getevents?那么如何修复我的程序以使其按预期工作呢?谢谢

您需要将 io_queue_run(3)io_queue_init(3) 集成到您的程序中。尽管这些不是新功能,但它们似乎并未出现在大量当前发布的发行版的联机帮助页中。这里有几个联机帮助页:

http://manpages.ubuntu.com/manpages/precise/en/man3/io_queue_run.3.html http://manpages.ubuntu.com/manpages/precise/en/man3/io_queue_init.3.html

当然,联机帮助页实际上并没有说明,但是 io_queue_run 调用了您在 io_set_callback 中设置的回调。

更新:呃。这是 Centos/RHEL 上 libaio-0.3.109 的 io_queue_run 的来源(LGPL 许可,版权所有 2002 Red Hat, Inc.)

int io_queue_run(io_context_t ctx)
{
    static struct timespec timeout = { 0, 0 };
    struct io_event event;
    int ret;

    /* FIXME: batch requests? */
    while (1 == (ret = io_getevents(ctx, 0, 1, &event, &timeout))) {
        io_callback_t cb = (io_callback_t)event.data;
        struct iocb *iocb = event.obj;

        cb(ctx, iocb, event.res, event.res2);
    }

    return ret;
}

如果没有 io_queue_wait 调用,您绝对不想真正调用它。而且,io_queue_wait 调用在 Centos/RHEL 6 和 7 中包含的 header 中被注释掉了。我认为你不应该调用这个函数。

相反,我认为您应该将此源合并到您自己的代码中,然后修改它以执行您想要的操作。您可以非常简单地向此 io_queue_run 添加一个超时参数,并用它替换对 io_getevents 的调用,而不是使用 io_queue_wait。这里甚至有一个补丁让 io_queue_run 变得更好:https://lwn.net/Articles/39285/).