如何实现异步非阻塞io.

netxuning 2009-10-09 04:55:45
如下代码,在键盘没有输入的时候select处于阻塞状态.
但根据网上的文章的描述,非阻塞异步io在等待io的过程中,进程可以做其它事情,而不是干巴巴地等待io的就绪。
所以我想知道,下面的代码如何更改才能实现异步非阻塞? 如何实现在等待io的时候进行别的操作?


#include <stdio.h>
#include <sys/select.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <assert.h>

int
main ()
{
int keyboard;
int ret, i, cnt;
char c;
fd_set readfd;
struct timeval timeout;
keyboard = open("/dev/tty", O_RDONLY | O_NONBLOCK);
assert(keyboard>0);
/*
while(1)
{
i = read(keyboard, &c, 1);
printf("%c \n", c);
}
*/

cnt = 0;
while(1) {
timeout.tv_sec = 1;
timeout.tv_usec = 0;
FD_ZERO(&readfd);
FD_SET(keyboard, &readfd);
printf("waiting for io ...\n");
ret = select(keyboard+1, &readfd, NULL, NULL, /*&timeout*/ NULL); //blocked without timeout
if(FD_ISSET(keyboard, &readfd)) {
printf("%d\n", ++cnt);
i = read(keyboard, &c, 1);
printf("read out:%d\n", i);
if('\n' == c)
continue;
//printf("the input is %c\n",c);
if ('q'==c)
break;
}
}

}
...全文
375 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
netxuning 2009-10-12
  • 打赏
  • 举报
回复
[Quote=引用 9 楼 zhuxueling 的回复:]
其实,多开一个线程进行select上的纯IO操作,就是异步IO了。
[/Quote]

好,谢谢,有没有什么源代码可以参考呢?
jiangfeng999 2009-10-12
  • 打赏
  • 举报
回复
linux下也有异步IO的函数库,楼主可以参考一下poll,aio_read,aio_write等函数
sumingspring 2009-10-10
  • 打赏
  • 举报
回复
顶一下,学习
zhuxueling 2009-10-10
  • 打赏
  • 举报
回复
异步IO与select,信号驱动IO不是一回事。
异步IO是完成时再通知,所以icop叫完成端口。
信号IO是发生时通知。之后事情要自己处理。
异步IO要用aio函数。
boost的asio是异步IO。
windows 的iocp是异步IO。
其实,多开一个线程进行select上的纯IO操作,就是异步IO了。
小魔菇 2009-10-10
  • 打赏
  • 举报
回复
好象要通过设置ioctl()来实现异步机制
dongjiawei316 2009-10-10
  • 打赏
  • 举报
回复
另外开一个线程好了,select阻塞住的时候,另一个线程还可以工作啊!
某鸟 2009-10-09
  • 打赏
  • 举报
回复
好像异步IO需要修改系统设置,一般linux系统默认不开这功能~
netxuning 2009-10-09
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 guosha 的回复:]
select实现不了异步非阻塞IO,异步非阻塞是要信号机制。
[/Quote]

能具体说说嘛?
HULIHONG 2009-10-09
  • 打赏
  • 举报
回复
顶一下,学习
快乐田伯光 2009-10-09
  • 打赏
  • 举报
回复
select实现不了异步非阻塞IO,异步非阻塞是要信号机制。

23,121

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧