linux_module_learn/device_model/my_device.c

71 lines
1.3 KiB
C
Raw Normal View History

2023-07-22 13:42:32 +08:00
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/cdev.h>
#include <linux/fs.h>
#include <linux/wait.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <linux/device.h>
#include "pub.h"
MODULE_LICENSE("GPL");
MODULE_AUTHOR("liuchao");
extern struct bus_type my_bus;
void my_dev_release(struct device *dev)
{
printk("%s-%s\n", __FILE__, __func__);
}
static struct device my_dev = {
.init_name = "my_dev",
.bus = &my_bus,
.release = my_dev_release,
};
unsigned long id = 0;
ssize_t my_dev_id_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
return sprintf(buf, "%d\n", id);
}
ssize_t my_dev_id_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
kstrtoul(buf, 10, &id);
return count;
}
DEVICE_ATTR(my_dev_id, S_IRUSR|S_IWUSR, my_dev_id_show, my_dev_id_store);
static __init int my_dev_init(void)
{
printk("my_dev init\n");
device_register(&my_dev);
device_create_file(&my_dev, &dev_attr_my_dev_id);
return 0;
}
module_init(my_dev_init);
static __exit void my_dev_exit(void)
{
printk("xdev exit\n");
device_remove_file(&my_dev, &dev_attr_my_dev_id);
device_unregister(&my_dev);
}
module_exit(my_dev_exit);