Chinaunix

标题: [请教]一个ioctl的问题,FIONREAD是什么含义? [打印本页]

作者: jeanlove    时间: 2008-11-01 22:09
标题: [请教]一个ioctl的问题,FIONREAD是什么含义?
如题,从"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 编辑 ]
作者: jeanlove    时间: 2008-11-02 19:11
dx能解释一下么? 在线等
作者: timespace    时间: 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.
作者: jeanlove    时间: 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里面没有实现,不知道我这个说法是否准确。
作者: singyea    时间: 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);
作者: jerrymy    时间: 2010-01-18 14:27
呵呵,明白了
作者: yrktcst    时间: 2011-07-01 11:40
回复 3# timespace


    焕然大悟




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2