免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 30326 | 回复: 6
打印 上一主题 下一主题

[请教]一个ioctl的问题,FIONREAD是什么含义? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-11-01 22:09 |只看该作者 |倒序浏览
如题,从"C专家编程"这本书上面摘下来的一个程序,功能是从读取键盘输入,每次按键都能得到字符,不用输入回车,不阻塞:
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<sys/ioctl.h>
  4. #include<errno.h>
  5. int kbhit(){
  6.   int i;
  7.   if(ioctl(0,FIONREAD,&i)<0){
  8.         printf("ioctl failed, error=%d\n ",errno);
  9.         exit(1);
  10.   }
  11.   return i;
  12. }
  13. main(){
  14. int i=0;
  15. int c=' ';
  16. system("stty raw -echo" );
  17. printf("enter 'q' to quit \n" );
  18. for(;c!='q';++i){
  19.   if(kbhit()){
  20.     c=getchar();
  21.     printf("\n got %c, on iteration %d",c,i);
  22.   }
  23. }
  24. system("stty cooked echo" );
  25. return 0;
  26. }
复制代码

---------------------------------
但是我运行这个程序确是100%cpu的死循环,不停的打印。

请问: ioctl函数的参数FIONREAD是什么意思,会导致什么特性?
如果我把  printf("\n got %c, on iteration %d",c,i);
这句话移到if的外面,就导致printf不停的打印,这又是为什么?

谢谢!

[ 本帖最后由 jeanlove 于 2008-11-1 22:17 编辑 ]

论坛徽章:
0
2 [报告]
发表于 2008-11-02 19:11 |只看该作者
dx能解释一下么? 在线等

论坛徽章:
11
技术图书徽章
日期:2014-03-01 14:44:34天蝎座
日期:2014-05-21 22:11:59金牛座
日期:2014-05-30 17:06:14
3 [报告]
发表于 2008-11-02 20:51 |只看该作者
FIONREAD
Return in the integer pointed to by the third argument to ioctl the number of bytes currently in the socket receive buffer. This feature also works for files, pipes, and terminals.

论坛徽章:
0
4 [报告]
发表于 2008-11-03 12:37 |只看该作者
原帖由 timespace 于 2008-11-2 20:51 发表
FIONREAD
Return in the integer pointed to by the third argument to ioctl the number of bytes currently in the socket receive buffer. This feature also works for files, pipes, and terminals.


谢谢,发现ioctl的这个参数用法似乎和流有关,这个FINOREAD在linux2.6.18(centOS5.2)里面的ioctl的man里面没有找到,在Solaris的ioctrl的man里面缺有。网上说这个特性在linux里面没有实现,不知道我这个说法是否准确。

论坛徽章:
0
5 [报告]
发表于 2008-11-13 15:49 |只看该作者
原帖由 timespace 于 2008-11-2 20:51 发表
FIONREAD
Return in the integer pointed to by the third argument to ioctl the number of bytes currently in the socket receive buffer. This feature also works for files, pipes, and terminals.


FIONREAD,就是返回缓冲区有多少字节。
输入有个输入缓冲区,用

ioctl(0,FIONREAD,&nread);

能得到缓冲区里面有多少字节要被读取。值放在 nread里面了。

然后就可以 read 了。nread = read(0,buffer,nread);

论坛徽章:
0
6 [报告]
发表于 2010-01-18 14:27 |只看该作者
呵呵,明白了

论坛徽章:
0
7 [报告]
发表于 2011-07-01 11:40 |只看该作者
回复 3# timespace


    焕然大悟
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP