首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >OS X上的来自文件的aio_read错误

OS X上的来自文件的aio_read错误
EN

Stack Overflow用户
提问于 2011-01-12 13:28:25
回答 2查看 1.3K关注 0票数 2

以下代码:

代码语言:javascript
复制
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <aio.h>
#include <errno.h>

int main (int argc, char const *argv[])
{
  char name[] = "abc";
  int fdes;
  if ((fdes = open(name, O_RDWR | O_CREAT, 0600 )) < 0)
    printf("%d, create file", errno);

  int buffer[] = {0, 1, 2, 3, 4, 5};
  if (write(fdes, &buffer, sizeof(buffer)) == 0){
    printf("writerr\n");
  }

  struct aiocb aio;
  int n = 2;
  while (n--){
    aio.aio_reqprio = 0;
    aio.aio_fildes = fdes;
    aio.aio_offset = sizeof(int);
    aio.aio_sigevent.sigev_notify = SIGEV_NONE; 

    int buffer2;
    aio.aio_buf = &buffer2;
    aio.aio_nbytes = sizeof(buffer2);

    if (aio_read(&aio) != 0){
      printf("%d, readerr\n", errno);
    }else{
      const struct aiocb *aio_l[] = {&aio};
      if (aio_suspend(aio_l, 1, 0) != 0){
         printf("%d, suspenderr\n", errno);
      }else{
        printf("%d\n", *(int *)aio.aio_buf);
      }
    }
  }

  return 0;
}

在Linux (Ubuntu9.10,用-lrt编译)上运行良好,打印

代码语言:javascript
复制
1
1

但是在OS X上失败了(10.6.6和10.6.5,我已经在两台机器上测试过了):

代码语言:javascript
复制
1
35, readerr

这可能是由于OS X上的某个库错误,还是我做错了什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-01-12 14:07:50

对于每个异步I/O操作,您需要恰好调用一次aio_return(2)。根据该手册页上的注释,如果不这样做,将会泄漏资源,而且显然也会导致您的问题。在调用aio_suspend等待I/O完成后,请确保调用aio_return来获取读取的字节数,例如:

代码语言:javascript
复制
const struct aiocb *aio_l[] = {&aio};
if (aio_suspend(aio_l, 1, 0) != 0)
{
  printf("aio_suspend: %s\n", strerror(errno));
}
else
{
  printf("successfully read %d bytes\n", (int)aio_return(&aio));
  printf("%d\n", *(int *)aio.aio_buf);
}

还要记住aio_read(2)手册页(重点是我的)中的这些重要说明:

aiocbp指向的异步I/O控制块结构,以及该结构的aiocbp->aio_buf成员引用的缓冲区必须保持有效,直到操作完成。因此,不鼓励对这些对象使用auto (堆栈)变量。

应该在aio_read()调用之前将异步I/O控制缓冲区aiocbp置零,以避免将伪造的上下文信息传递给内核。

票数 5
EN

Stack Overflow用户

发布于 2011-01-12 14:02:38

尝试将struct aiocb aio置零

该手册上写道:

代码语言:javascript
复制
RESTRICTIONS
[...]
     The asynchronous I/O control buffer aiocbp should be zeroed before the
     aio_read() call to avoid passing bogus context information to the kernel.
[...]
BUGS
     Invalid information in aiocbp->_aiocb_private may confuse the kernel.
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4665618

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档