- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
以下代码:
#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 上的某些库错误,还是我做错了什么?
最佳答案
您需要调用aio_return(2)
每个异步 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);
}
另请记住 aio_read(2)
中的这些重要说明手册页(强调我的):
The Asynchronous I/O Control Block structure pointed to by
aiocbp
and the buffer that theaiocbp->aio_buf
member of that structure references must remain valid until the operation has completed. For this reason, use of auto (stack) variables for these objects is discouraged.The asynchronous I/O control buffer
aiocbp
should be zeroed before theaio_read()
call to avoid passing bogus context information to the kernel.
关于c - aio_read from OS X 上的文件错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4665618/
我将使用 aio 进行异步读取。当 aio 完成并触发信号处理程序时,我可能需要执行另一个 aio_read 调用并继续。 aio_read 未在安全函数中提及(在 man 信号中)。不过,普通阅读是
我有一个启动 aio_read 任务并返回主程序的函数。 我想定期检查任务是否完成以关闭文件描述符并可能通知用户。 我当前的方法是声明一个 struct,其中包含任务的 struct aiocb 和文
谁在执行阅读任务?是内核吗?任务在哪里排队?所有进程的队列是否相同? http://linux.die.net/man/3/aio_read The aio_read() function queue
我正在尝试使用 C++ 异步读取和写入磁盘(使用 Ubuntu 10.04 中的 posix aio 库),遵循此处概述的说明:aio tutorial .我可以异步读写,但恐怕会出现某种小的内存泄漏
我实现了需要读写的游戏服务器。所以我接受传入连接并使用 aio_read() 开始读取它,但是当我需要发送一些东西时,我停止使用 aio_cancel() 读取然后使用 aio_write ()。在
以下代码: #include #include #include #include #include int main (int argc, char const *argv[]) {
在 aio_read 中,我们在 aiocb 结构上使用 aio_error 函数来检查操作是否完成。对我来说,这似乎与轮询和读取相同,然后检查 EWOULDBLOCK 作为返回值。 最佳答案 we
我是一名优秀的程序员,十分优秀!