C OS X上的aio_从文件读取错误
以下代码:C OS X上的aio_从文件读取错误,c,linux,macos,file-io,aio,C,Linux,Macos,File Io,Aio,以下代码: #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,
#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;
}
但在OS X 10.6.6和10.6.5上失败,我已经在两台机器上进行了测试:
1
35, readerr
这可能是由于OS X上的某个库错误造成的,还是我做错了什么?尝试将结构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.
您需要为每个异步I/O操作准确调用一次。根据该手册页上的说明,不这样做将导致资源泄漏,而且显然也会导致您的问题。调用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);
}
还要记住手册页中的这些重要注释:
aiocbp指向的异步I/O控制块结构和
该结构的aiocbp->aio_buf成员必须引用的缓冲区
在操作完成之前保持有效。因此,使用
不建议为这些对象自动堆叠变量
异步I/O控制缓冲区aiocbp应在
aio_read调用以避免向内核传递虚假的上下文信息
仅供参考,35是EAGAIN,由于系统资源限制,规范读取,请求未排队..更改为类似于aio=mallocsizeofstruct aiocb;memsetaio,0,sizeofstruct aiocb;这没用,那一定是另外一回事。谢谢,回来救了我一天。我知道堆栈的缺点,但这不是问题,因为我总是在开始阅读之后等待阅读完成。我知道,这是一个愚蠢的家庭作业。
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);
}