-
#include <linux/module.h>
-
#include <linux/kernel.h>
-
#include <linux/fs.h>
-
#include <linux/cdev.h>
-
#include <linux/init.h>
-
-
static struct cdev chr_dev; //cdev是设备在内核中的内部结构
-
static dev_t ndev; //设备编号
-
-
static int chr_open(struct inode *nd, struct file *filp)
-
{
-
int major = MAJOR(nd -> i_rdev); //表示设备的inode的字段中的i_rdev保存了真正的设备编号
-
int minor = MINOR(nd -> i_rdev);
-
printk("chr_open, major = %d , minor = %d\n.", major, minor);
-
return 0;
-
}
-
-
static ssize_t chr_read(struct file *f, char __user *u, size_t sz, loff_t *off)
-
{
-
printk("In the chr_read() function!\n");
-
-
return 0;
-
}
-
-
struct file_operations chr_ops =
-
{
-
.owner = THIS_MODULE, //避免模块的操作正在被使用时卸载该模块
-
.open = chr_open,
-
.read = chr_read,
-
};
-
-
static int demo_init(void)
-
{
-
int ret;
-
cdev_init(&chr_dev, &chr_ops); //字符设备cdev初始化,建立cdev和file_operations之间的连接
-
ret = alloc_chrdev_region(&ndev, 0 , 1 ,"chr_dev"); //第一个参数类型是dev_t *是输出参数动态分配的设备编号,最后为设备名
-
-
if (ret < 0)
-
return ret;
-
-
printk("demo_init(): major = %d ,minot = %d\n", MAJOR(ndev), MINOR(ndev)); //两个宏分别获得设备的主次编号
-
ret = cdev_add(&chr_dev, ndev, 1); //将设备添加到系统中,需要失败检查
-
if (ret < 0)
-
return ret;
-
-
return 0;
-
}
-
-
static void demo_exit(void)
-
{
-
printk("Removing chr_dev module...\n");
-
cdev_del(&chr_dev); //移除字符设备
-
unregister_chrdev_region(ndev, 1); //释放设备编号
-
}
-
-
module_init(demo_init);
-
module_exit(demo_exit);
-
-
MODULE_LICENSE("GPL");
-
ifneq ($(KERNELRELEASE),)
-
obj-m := demo_chr_dev.o
-
else
-
KERNELDIR ?= /lib/modules/$(shell uname -r)/build
-
PWD := $(shell pwd)
-
-
default:
-
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
-
endif
-
#include <stdio.h>
-
#include <fcntl.h>
-
#include <unistd.h>
-
-
#define CHR_DEV_NAME "/dev/chr_dev"
-
-
int main()
-
{
-
int ret;
-
char buf[32];
-
int fd = open(CHR_DEV_NAME, O_RDONLY | O_NDELAY);
-
if (fd < 0)
-
{
-
printf("open file faild!\n");
-
return -1;
-
}
-
-
read(fd ,buf, 32);
-
close(fd);
-
-
return 0;
-
}
#insmod demo_chr_dev.ko
demo_init(): major = 248, minor = 0
#mknod /dev/chr_dev c 248 0 //动态分配设备号无法预先创建设备节点
#./main
阅读(2283) | 评论(0) | 转发(0) |