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

从ELDD上看到的,人家总结的很全很好很强大,这里拿来用了
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的一部分)的秒


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

阅读终点,创作起航,您可以撰写心得或摘录文章要点写篇博文。去创作
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Linux 上,可以通过文件系统访问 I/O 端口,但需要使用特定的设备驱动程序。在 Qt 中,可以通过 QIODevice 类来访问设备驱动程序。 以下是一个使用 QIODevice 类 I/O 端口的示例代码: ```cpp #include <QtCore> #include <sys/io.h> class IoDevice : public QIODevice { public: IoDevice(quint16 port, QObject* parent = nullptr) : QIODevice(parent), m_port(port) { if (ioperm(m_port, 1, 1) != 0) { qFatal("ioperm failed"); exit(1); } } ~IoDevice() { ioperm(m_port, 1, 0); } protected: qint64 readData(char* data, qint64 maxSize) override { unsigned char ch = inb(m_port); *data = ch; return 1; } qint64 writeData(const char* data, qint64 maxSize) override { unsigned char ch = *data; outb(ch, m_port); return 1; } private: quint16 m_port; }; int main(int argc, char** argv) { QCoreApplication app(argc, argv); IoDevice ioDevice(0x378); if (!ioDevice.open(QIODevice::ReadWrite)) { qFatal("Failed to open I/O device"); exit(1); } char data; if (ioDevice.read(&data, 1) == 1) { qDebug() << "Read data:" << data; } char sendData = 0x55; if (ioDevice.write(&sendData, 1) == 1) { qDebug() << "Write data:" << sendData; } ioDevice.close(); return app.exec(); } ``` 上述示例代码中,我们创建了一个名为 `IoDevice` 的自定义 `QIODevice` 类。在构造函数中,我们使用 `ioperm` 函数请求访问 I/O 端口。在析构函数中,我们释放了对 I/O 端口的访问。在 `readData` 和 `writeData` 函数中,我们分别使用 `inb` 和 `outb` 函数 I/O 端口。在 `main` 函数中,我们创建了 `IoDevice` 类的实例,并使用 `open` 函数打开 I/O 端口。然后,我们使用 `read` 函数取一个字节的数据,并使用 `write` 函数入一个字节的数据。最后,我们关闭了 `IoDevice` 类的实例。 需要注意的是,访问 I/O 端口需要特权级别较高的权限,因此需要使用 root 权限运行程序

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值