ioctl之FIONREAD


在學習ioctl 時常常跟 read, write 混淆。其實 ioctl 是用來設置硬件控制寄存器,或者讀取硬件狀態寄存器的數值之類的。

而read,write 是把數據丟入緩沖區,硬件的驅動從緩沖區讀取數據一個個發送或者把接收的數據送入緩沖區。

 ioctl(keyFd, FIONREAD, &b)

得到緩沖區里有多少字節要被讀取,然后將字節數放入b里面。

接下來就可以用read了。

read(keyFd, &b, sizeof(b))

這兩個可以用在按鍵控制上,先是檢測按鍵是否被按下,如果被按下就放在B里,然后user 在讀取按鍵對應數值。

Listing - Getting the number of bytes in the input buffer. 
清單 - 讀取串行端口輸入緩沖區中的字節數 
#include <unistd.h> 
#include <termios.h> 
int fd; 
int bytes; 
ioctl(fd, FIONREAD, &bytes);  

eg:

 

#include<stdio.h>

#include<stdlib.h>

#include<sys/ioctl.h>

#include<errno.h>

int kbhit(){

  int i;

  if(ioctl(0,FIONREAD,&i)<0){

        printf("ioctl failed, error=%d\n ",errno);

        exit(1);

  }

  return i;

}

main(){

int i=0;

int c=' ';

system("stty raw -echo" );

printf("enter 'q' to quit \n" );

for(;c!='q';++i){

  if(kbhit()){

    c=getchar();

    printf("\n got %c, on iteration %d",c,i);

  }

}

system("stty cooked echo" );

return 0;

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM