首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Linux设备驱动函数中,如何知道从机号或为哪个特定设备调用了该驱动函数?

在Linux设备驱动函数中,如何知道从机号或为哪个特定设备调用了该驱动函数?
EN

Stack Overflow用户
提问于 2014-06-03 22:47:44
回答 2查看 1.4K关注 0票数 0

如果有下面提到的三个I2C设备,并且在设备驱动程序init()函数中,将调用下面的register_chrdev(89,"i2c",&i2cfops)。注意,名称是"i2c“,而不是"i2c-0"/"i2c-1"/"i2c-2”。在i2cdriver_open或i2cdriver_ioctl函数中,驱动器如何知道次要编号或为哪个I2C设备调用了该函数?

有关更多详细信息,请参阅以下内容。

代码语言:javascript
复制
crw-r--r--    1 0        0         89,   0 Jun 12 09:15 /dev/i2c-0
crw-r--r--    1 0        0         89,   1 Jun 12 09:15 /dev/i2c-1
crw-r--r--    1 0        0         89,   2 Jun 12 09:15 /dev/i2c-2

应用程序:

代码语言:javascript
复制
int main(void)
{
  int fd;
  fd = open("/dev/i2c-0");
  (void) ioctl(fd, ...);
  return 0;
}

驱动程序:

代码语言:javascript
复制
static struct file_operations i2cfops;
int i2cdriver_open(struct inode * inodePtr, struct file * filePtr);
int i2cdriver_ioctl(struct inode * inodePtr, struct file * filePtr, unsigned int ui, unsigned long ul);
int driver_init(void)
{
  i2cfops.open = &i2cdriver_open;
  i2cfops.ioctl = &i2cdriver_ioctl;
  (void) register_chrdev(89, "i2c", &i2cfops);
  return 0;
}
int i2cdriver_open(struct inode * inodePtr, struct file * filePtr)
{
  /*In here, how to know the minor number or for which I2C device this function has been invoked?*/
}
int i2cdriver_ioctl(struct inode * inodePtr, struct file * filePtr, unsigned int ui, unsigned long ul)
{
  /*In here, how to know the minor number or for which I2C device this function has been invoked?*/
}
EN

回答 2

Stack Overflow用户

发布于 2014-07-22 02:39:53

一般来说,当您发布有关Linux内核/驱动程序开发的问题时,请始终包含您正在使用的内核版本。这会让你更容易得到适合你的内核的答案。

这应该能够检索您的次要号码:

代码语言:javascript
复制
/* Add this header if you don't already have it included */
#include <linux/kdev_t.h>

/* Add this macro function wherever you need the minor number */
unsigned int minor_num = MINOR(inodePtr -> i_rdev);

This page具有次宏的定义,而this page具有inode结构的定义以供参考。

票数 1
EN

Stack Overflow用户

发布于 2020-04-29 14:20:38

当您使用相同的设备驱动程序创建多个设备节点时,您将拥有多个具有相同主编号但不同次要编号的设备。

要检索其中哪个特定的设备被调用,您只需要知道在文件open()函数中调用的设备的次要设备号。

代码语言:javascript
复制
#include <kdev_t.h>
unsigned int minor_num;
static int file_open(struct inode *inode, struct file *file){
   /*The line below is to be written in your open function*/
   minor_num = MINOR(inode->i_rdev);
   printk(KERN_INFO "Device file opened\n");
   return 0;
}

这将为您提供可用于执行任何特定于设备的任务的设备编号。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24018235

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档