IOCTL Linux 设备驱动程序 [英] IOCTL Linux device driver
问题描述
谁能给我解释一下,
- 什么是
IOCTL
? - 它有什么用?
- 我该如何使用它?
- 为什么我不能定义与
IOCTL
一样工作的新函数?
- What is
IOCTL
? - What is it used for?
- How can I use it?
- Why can't I define new function that does the same work as
IOCTL
?
推荐答案
一个ioctl
,意思是输入-输出控制"是一种特定于设备的系统调用.Linux 中只有少数系统调用(300-400),不足以表达设备可能具有的所有独特功能.因此,驱动程序可以定义一个 ioctl,它允许用户空间应用程序向它发送命令.然而,ioctl 不是很灵活,而且往往会变得有点混乱(几十个神奇数字"不管用……还是不行),而且也可能不安全,因为您将缓冲区传递给内核 - 处理不当可能会破坏事情很容易.
An ioctl
, which means "input-output control" is a kind of device-specific system call. There are only a few system calls in Linux (300-400), which are not enough to express all the unique functions devices may have. So a driver can define an ioctl which allows a userspace application to send it orders. However, ioctls are not very flexible and tend to get a bit cluttered (dozens of "magic numbers" which just work... or not), and can also be insecure, as you pass a buffer into the kernel - bad handling can break things easily.
另一种方法是 sysfs
接口,您可以在其中设置 /sys/
下的文件,然后读取/写入该文件以从驱动程序获取信息以及向驱动程序获取信息.如何设置的示例:
An alternative is the sysfs
interface, where you set up a file under /sys/
and read/write that to get information from and to the driver. An example of how to set this up:
static ssize_t mydrvr_version_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%s
", DRIVER_RELEASE);
}
static DEVICE_ATTR(version, S_IRUGO, mydrvr_version_show, NULL);
在驱动程序设置期间:
device_create_file(dev, &dev_attr_version);
然后,您将在 /sys/
中为您的设备创建一个文件,例如,/sys/block/myblk/version
用于块驱动程序.
You would then have a file for your device in /sys/
, for example, /sys/block/myblk/version
for a block driver.
另一种更频繁使用的方法是 netlink,它是一种 IPC(进程间通信)方法,可通过 BSD 套接字接口与驱动程序通信.例如,这由 WiFi 驱动程序使用.然后,您可以使用 libnl
或 libnl3
库从用户空间与它通信.
Another method for heavier use is netlink, which is an IPC (inter-process communication) method to talk to your driver over a BSD socket interface. This is used, for example, by the WiFi drivers. You then communicate with it from userspace using the libnl
or libnl3
libraries.
这篇关于IOCTL Linux 设备驱动程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!