ioctl初步理解

ioctl系统调用是为用户空间建立的一种控制硬件设备的通道。比如控制串口的波特率,马达的转速等等。
是用户空间和内核空间进行通讯的方式之一。要实现一个ioctl,需要用户空间和内核空间两方面的配合。
如果想要一个硬件支持ioctl,则要在其驱动函数中加入ioctl的实现,应用程序想要通过ioctl控制一个设备,
则要在用户空间发起一个iotcl系统调用。
它在用户空间的系统调用函数原型为:
 int ioctl ( int fd, unsigned long cmd, ...);
对应到内核空间的驱动函数为:
int (*ioctl) ( stuct inode *inode, struct file *filep,
            unsigned int cmd, unsigned long arg);

两个函数是通过驱动程序中的:
struct file_operations
结构体联系起来的,如:
struct file_operations Fops = {
    .ioctl = device_ioctl,
    .open = device_open,
    .release = device_release,
};
由此可以看出ioctl是通过文件来联系起来的,这样就要求我们的设备要有文件的表示形式,也就是要在/dev
下生成设备节点。驱动程序需要用以下函数实现这一要求:
int    alloc_chrdev_region(dev_t *dev,unsigned int firstminor,unsigned int count,char *name);
void cdev_init (struct cdev      *cdev, const struct file_operations *fops);
int    cdev_add (struct cdev    * p,   dev_t   dev,   unsigned      count);
struct class    *class_create(struct module *owner, const char *name);
struct device *device_create(struct class *class, struct device *parent,
                             dev_t devt, void *drvdata, const char *fmt, ...);

这样就可以在自己的驱动程序中定义自己的ioctl函数了。
在这个例子中,此函数的实现就是  device_ioctl ,这个函数就要符合
int (*ioctl) ( stuct inode *inode, struct file *filep,
            unsigned int cmd, unsigned long arg);
的形式了。

系统是怎么知道内核空间的ioctl就是要操作这个驱动而不是那个驱动呢,这就是靠其参数fd来实现了。
应用程序首先通过open函数打开设备获得fd,内核再通过fd确定设备的文件描述符,进而通过设备文件名来找到具体设备。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值