自动创建设备节点
android的ueventd守护进程会对”/sys/class““/sys/block”“/sys/devices”三个目录扫描,打开所有子目录中的uevent属性文件,写入"add"命令,然后驱动会发出uevent事件,ueventd进程捕捉到后,自动创建设备节点。
所以可以通过class_create创建一个类,这个类会在”/sys/class“目录下显示,然后在这个类下面创建设备,这样ueventd进程可以扫描该设备节点下的uevent节点到dev目录下自动创建设备节点
#include <linux/init.h>
#include <linux/module.h>
#include <linux/major.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/types.h>
#include <linux/fs.h>
#define TAG "hello"
static int hello_major;
static struct cdev hello_cdev;
static struct class *hello_class;
static ssize_t hello_read(struct file *file, char __user *buffer,
size_t count, loff_t *ppos)
{
printk(TAG" func:%s line:%d\n", __func__, __LINE__);
return count;
}
ssize_t hello_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos)
{
printk(TAG" func:%s line:%d\n", __func__, __LINE__);
return count;
}
static int hello_open(struct inode *inode, struct file *file)
{
printk(TAG" func:%s line:%d\n", __func__, __LINE__);
return 0;
}
static int hello_release(struct inode *inode, struct file *file)
{
printk(TAG" func:%s line:%d\n", __func__, __LINE__);
return 0;
}
static const struct file_operations hello_ops = {
.owner = THIS_MODULE,
.read = hello_read,
.write = hello_write,
.open = hello_open,
.release = hello_release,
};
static int hello_init(void)
{
int retval;
dev_t dev_id;
printk(TAG" func:%s line:%d\n", __func__, __LINE__);
retval = alloc_chrdev_region(&dev_id, 0, 1, "hello");
hello_major = MAJOR(dev_id);
printk(TAG"major is %d\n", hello_major);
if (retval < 0) {
printk(TAG"can't get major number\n");
goto error;
}
cdev_init(&hello_cdev, &hello_ops);
retval = cdev_add(&hello_cdev, dev_id, 1);
if (retval < 0) {
printk(TAG"cannot add cdev\n");
goto cleanup_alloc_chrdev_region;
}
hello_class = class_create(THIS_MODULE, "hello");
if (IS_ERR(hello_class)) {
printk(TAG "Error creating hello class.\n");
cdev_del(&hello_cdev);
retval = PTR_ERR(hello_class);
goto cleanup_alloc_chrdev_region;
}
device_create(hello_class, NULL, MKDEV(hello_major, 0), NULL, "hello0");
return 0;
cleanup_alloc_chrdev_region:
unregister_chrdev_region(dev_id, 1);
error:
return retval;
}
static void hello_exit(void)
{
dev_t dev_id = MKDEV(hello_major, 0);
device_destroy(hello_class, MKDEV(hello_major, 0));
class_destroy(hello_class);
cdev_del(&hello_cdev);
unregister_chrdev_region(dev_id, 1);
printk(TAG" func:%s line:%d\n", __func__, __LINE__);
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
加载驱动程序后,可以看到/dev/hello0节点自动创建了
测试程序
int main(int argc, char **argv)
{
int fd;
char buf = '1';
if(argc != 2) {
printf("Usage: %s [node]\n", argv[0]);
exit(1);
}
fd = open(argv[1], O_RDWR);
if (fd < 0) {
printf("open %s failed\n", argv[1]);
}
write(fd, &buf, 1);
read(fd, &buf, 1);
close(fd);
return 0;
}
编译好测试程序,假如编译好的程序名为testhello,push到机器里,运行
./testhello /dev/hello0
观察log,可以看出,应用层通过系统调用可以调用到驱动file_operations结构体里对应的函数
问题
可以一次性创建多个设备,共用相同的file_operations结构体里的函数吗?