Linux用户态程序读写IO端口方法总结

来源:互联网 发布:csgo网络很卡 编辑:程序博客网 时间:2024/05/18 18:00

http://blog.csdn.net/deep_pro/archive/2010/02/22/5315655.aspx

 

1、使用ioperm() and iopl()来获得权限,然后To write data to an I/O port, use outb()outw()outl(), or their cousins. To read data from a port, use inb()inw()inl(), or their relatives.这种方法只在x86上有效
附带一个例子,读取pc兼容机上的rtc时钟(属于cmos的一部分)的秒

view plaincopy to clipboardprint?
  1. #include <sys/io.h>  
  2. #include <unistd.h>  
  3. #include <stdio.h>  
  4. #include <stdlib.h>  
  5.   
  6. void dump_port(unsigned char addr_port, unsigned char data_port,  
  7.           unsigned short offset, unsigned short length)  
  8. {  
  9. unsigned char i, *data;  
  10.   
  11. if (!(data = (unsigned char *)malloc(length)))  
  12.     {  
  13.       perror("Bad Malloc/n");  
  14.       exit(1);  
  15.     }  
  16.   
  17. /* Write the offset to the index port 
  18.      and read data from the data port */  
  19. for (i=offset; i<offset+length; i++)  
  20.     {  
  21.       outb(i, addr_port );  
  22.       data[i-offset] = inb(data_port);  
  23.     }  
  24.   
  25. /* Dump */  
  26. for (i=0; i<length; i++)  
  27.     printf("%02X/n", data[i]);  
  28.   
  29. free(data);  
  30. }  
  31.   
  32. int main(int argc, char *argv[])  
  33. {  
  34.   
  35. /* Get access permissions */  
  36. if ( iopl(3) < 0)  
  37.     {  
  38.       perror("iopl access error/n");  
  39.       exit(1);  
  40.     }  
  41. while (1)  
  42.     {  
  43.       dump_port(0x70, 0x71, 0x0, 1);  
  44.       sleep(1);  
  45.     }  
  46. }  

 

2、使用/dev/port 这个由内核提供的驱动,这比前一种方式会损失一些性能,好处是比ioperm() and iopl()得到更加有效的权限管理

view plaincopy to clipboardprint?
  1. #include <unistd.h>  
  2. #include <fcntl.h>  
  3. #include <stdlib.h>  
  4. #include <unistd.h>  
  5.   
  6.   
  7. int main(int argc, char *argv[])  
  8. {  
  9. char seconds=0;  
  10. char data = 0;  
  11. int fd = open("/dev/port", O_RDWR);  
  12.   
  13. while (1)  
  14.     {  
  15.       lseek(fd, 0x70, SEEK_SET);  
  16.       write(fd, &data, 1);  
  17.   
  18.       lseek(fd, 0x71, SEEK_SET);  
  19.       read(fd, &seconds, 1);  
  20.       printf("%02X/n", seconds);  
  21.       sleep(1);  
  22.     }  
  23. }