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

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的一部分)的秒

  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()得到更加有效的权限管理

  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. }  

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值