以下代码:
#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(Ubuntu 9.10,使用-lrt编译),打印
1
1
但OS X上失败了(10.6.6和10.6.5,我在两台机器上测试过):
1
35, readerr
这可能是因为OS X上的某些库错误,还是我做错了什么?
答案 0 :(得分:5)
您需要为每个异步I / O操作调用aio_return(2)
一次。根据该手册页上的说明,如果不这样做会泄漏资源,这显然也会导致您的问题。在调用aio_suspend
等待I / O完成后,请务必调用aio_return
以获取读取的字节数,例如:
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
成员引用的缓冲区必须 在操作完成之前一直有效。出于这个原因,使用 不建议使用这些对象的自动(堆栈)变量。异步I / O控制缓冲区
aiocbp
应该在之前归零aio_read()
调用以避免将伪造的上下文信息传递给内核。
答案 1 :(得分:0)
尝试归零struct aiocb aio
?
手册上写着:
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.