在Linux设备驱动程序功能中,如何知道次要号或已针对哪个特定设备调用了该驱动程序功能?

问题描述 投票:0回答:2

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

请参阅下面的更多详细信息。

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

应用程序:

int main(void)
{
  int fd;
  fd = open("/dev/i2c-0");
  (void) ioctl(fd, ...);
  return 0;
}

驱动程序:

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?*/
}
linux driver device
2个回答
2
投票

作为一般说明,每当您发布有关Linux内核/驱动程序开发的问题时,请始终包括您使用的内核版本。它使为您的答案真正适用于您的内核变得容易得多。

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

/* 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具有MINOR宏的定义,this page具有inode结构的定义以供参考。


0
投票

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

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

#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;
}

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

© www.soinside.com 2019 - 2024. All rights reserved.