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的一部分)的秒
- #include <sys/io.h>
- #include <unistd.h>
- #include <stdio.h>
- #include <stdlib.h>
- void dump_port(unsigned char addr_port, unsigned char data_port,
- unsigned short offset, unsigned short length)
- {
- unsigned char i, *data;
- if (!(data = (unsigned char *)malloc(length)))
- {
- perror("Bad Malloc/n");
- exit(1);
- }
- /* Write the offset to the index port
- and read data from the data port */
- for (i=offset; i<offset+length; i++)
- {
- outb(i, addr_port );
- data[i-offset] = inb(data_port);
- }
- /* Dump */
- for (i=0; i<length; i++)
- printf("%02X/n", data[i]);
- free(data);
- }
- int main(int argc, char *argv[])
- {
- /* Get access permissions */
- if ( iopl(3) < 0)
- {
- perror("iopl access error/n");
- exit(1);
- }
- while (1)
- {
- dump_port(0x70, 0x71, 0x0, 1);
- sleep(1);
- }
- }
2、使用/dev/port 这个由内核提供的驱动,这比前一种方式会损失一些性能,好处是比ioperm() and iopl()得到更加有效的权限管理
- #include <unistd.h>
- #include <fcntl.h>
- #include <stdlib.h>
- #include <unistd.h>
- int main(int argc, char *argv[])
- {
- char seconds=0;
- char data = 0;
- int fd = open("/dev/port", O_RDWR);
- while (1)
- {
- lseek(fd, 0x70, SEEK_SET);
- write(fd, &data, 1);
- lseek(fd, 0x71, SEEK_SET);
- read(fd, &seconds, 1);
- printf("%02X/n", seconds);
- sleep(1);
- }
- }