一个物理设备 - >两个字符设备

时间:2013-07-05 14:06:15

标签: c linux embedded hardware

我有一些gpio设备。 我有一个用于处理此设备的内核模块。

//headers
#include <linux/module.h>
#include <linux/init.h>
...

//declarations 
static si_t *gpio_sih;
static int gpio_major;
static struct class *gpiodev_class = NULL;

//some functions for open, read, write, etc
...

static struct file_operations gpio_fops = {...} // <- look up 

static int __init
gpio_init(void)
{
    if (!(gpio_sih = si_kattach(SI_OSH)))
        return -ENODEV;
    if ((gpio_major = register_chrdev(0, "gpio", &gpio_fops)) < 0)
        return gpio_major;
    gpiodev_class = class_create(THIS_MODULE, "gpio");
    if (IS_ERR(gpiodev_class)) {
        printk("Error creating gpio class\n");
        return -1;
    }
    class_device_create(gpiodev_class, NULL, MKDEV(gpio_major, 0), NULL, "gpio");
    return 0;
}

static void __exit
gpio_exit(void)
{
    if (gpiodev_class != NULL) {
        class_device_destroy(gpiodev_class, MKDEV(gpio_major, 0));
        class_destroy(gpiodev_class);
    }
    gpiodev_class = NULL;
    if (gpio_major >= 0)
        unregister_chrdev(gpio_major, "gpio");
    si_detach(gpio_sih);
}

module_init(gpio_init);
module_exit(gpio_exit);

我还需要另一个内核模块来处理这个物理设备,但它必须是系统中另一个具有另一个文件操作的字符设备。我该怎么办?通过类比写一个模块?

//headers
#include <linux/module.h>
#include <linux/init.h>
...

//declarations 
static si_t *another_gpio_sih;
static int another_gpio_major;
static struct class *another_gpiodev_class = NULL;

//some functions for another_open, another_read, another_write, another_etc
...

static struct file_operations another_gpio_fops = {...} // <- look up 

static int __init
another_gpio_init(void)
{
    if (!(another_gpio_sih = si_kattach(SI_OSH)))
        return -ENODEV;
    if ((another_gpio_major = register_chrdev(0, "another_gpio", &another_gpio_fops)) < 0)
        return gpio_major;
    another_gpiodev_class = class_create(THIS_MODULE, "another_gpio");
    if (IS_ERR(another_gpiodev_class)) {
        printk("Error creating gpio class\n");
        return -1;
    }
    class_device_create(another_gpiodev_class, NULL, MKDEV(another_gpio_major, 0), NULL, "another_gpio");
    return 0;
}

static void __exit
another_gpio_exit(void)
{
    if (another_gpiodev_class != NULL) {
        class_device_destroy(another_gpiodev_class, MKDEV(another_gpio_major, 0));
        class_destroy(another_gpiodev_class);
    }
    another_gpiodev_class = NULL;
    if (another_gpio_major >= 0)
        unregister_chrdev(another_gpio_major, "another_gpio");
    si_detach(another_gpio_sih);
}

module_init(another_gpio_init);
module_exit(another_gpio_exit);

还是使用导出全局变量?

EXPORT_SYMBOL(gpio_sih);
EXPORT_SYMBOL(gpiodev_class);

extern static si_t *another_gpio_sih;
extern static struct class *another_gpiodev_class;

感谢。

1 个答案:

答案 0 :(得分:0)

首先为什么需要所有这些设备?为什么不使用标准内核接口: / SYS /类/ GPIO?

它允许用户空间读取,写入和等待gpio的更改。

二。如果你有两个具有几乎相同功能的角色设备,为什么不在一个驱动程序中处理它们, 设置一个主要数字和两个不同的次要数字,从file_operation正确实现开放模拟,一切都会好的。