#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fcntl.h>
#include <linux/device.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <asm/uaccess.h>
#define DEVICE_NAME "hello"
#define HELLO_MAJOR 249
static int hello_major = HELLO_MAJOR;
static struct cdev hello_dev;
MODULE_LICENSE("GPL");
static int hello_open(struct inode *inode, struct file *file)
{
return 0;
}
static int hello_release(struct inode *inode, struct file *file)
{
return 0;
}
static ssize_t hello_read(struct file *file, char *buf, size_t cnt, loff_t *offset)
{
return 0;
}
static ssize_t hello_write(struct file *file, const char *buf, size_t cnt, loff_t *offset)
{
return 0;
}
static int hello_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
{
return 0;
}
static struct file_operations hello_fops = {
.owner = THIS_MODULE,
.read = hello_read,
.write = hello_write,
.release = hello_release,
.open = hello_open,
.ioctl = hello_ioctl, // 新版本内核使用 .unlocked_ioctl =
};
static int __init my_hello_module_init(void)
{
int res = -1;
int err;
dev_t dev = MKDEV(hello_major,0);
if(hello_major)
res = register_chrdev_region(dev,1,DEVICE_NAME);
else{
res = alloc_chrdev_region(&dev,0,1,DEVICE_NAME);
}
if(res < 0)
{
printk("Can't allocate major number for hello device\r\n");
return res;
}
memset(&hello_dev,0,sizeof(hello_dev));
/*初始化并添加cdev结构体*/
cdev_init(&hello_dev,&hello_fops);
hello_dev.owner = THIS_MODULE;
hello_dev.ops = &hello_fops;
err = cdev_add(&hello_dev,dev,1);
if(err){
printk("Add hello device error %d\n",err);
}
printk("Hello, my module is installed !\n");
return 0;
}
static void __exit my_hello_module_cleanup(void)
{
dev_t dev;
cdev_del(&hello_dev);
dev = MKDEV(hello_major, 0);
unregister_chrdev_region(dev, 1);
printk("Good-bye, my module was removed!\n");
}
module_init(my_hello_module_init);
module_exit(my_hello_module_cleanup);
hello 驱动模块
最新推荐文章于 2021-05-01 04:56:29 发布