w@w:~/linux_kernel/dev_t$ cat hello.c
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kdev_t.h>
#include <linux/fs.h>
static int major = 233; //主设备号
static int minor = 0; //次设备号
static dev_t devno; //定义设备号变量
static int hello_init(void)
{
int result;
printk("hello_init \n");
devno = MKDEV(major,minor); //创建主次设备号
result = register_chrdev_region(devno, 1, "test"); //注册设备号, 1:代表注册一个设备,名称叫test
if(result<0) //创建成功为0,失败一般为负值
{
printk("register_chrdev_region fail \n");
return result;
}
return 0;
}
static void hello_exit(void) //设备号也是资源,不用必须删除注销
{
printk("hello_exit \n");
unregister_chrdev_region(devno,1);
return;
}
module_init(hello_init);
module_exit(hello_exit);
//proc/devices
Makefile
w@w:~/linux_kernel/dev_t$ cat Makefile
ifneq ($(KERNELRELEASE),)
$(info "2nd")
obj-m:=hello.o
else
KDIR :=/lib/modules/$(shell uname -r)/build
PWD :=$(shell pwd)
all:
$(info "1st")
make -C $(KDIR) M=$(PWD) modules
clean:
rm -f *.ko *.o *.mod.o *.symvers *.cmd *.mod.c *.order
endif
w@w:~/linux_kernel/dev_t$ sudo make
"1st"
make -C /lib/modules/5.4.0-104-generic/build M=/home/w/linux_kernel/dev_t modules
make[1]: Entering directory '/usr/src/linux-headers-5.4.0-104-generic'
"2nd"
CC [M] /home/w/linux_kernel/dev_t/hello.o
"2nd"
Building modules, stage 2.
MODPOST 1 modules
WARNING: modpost: missing MODULE_LICENSE() in /home/w/linux_kernel/dev_t/hello.o
see include/linux/module.h for more information
CC [M] /home/w/linux_kernel/dev_t/hello.mod.o
LD [M] /home/w/linux_kernel/dev_t/hello.ko
加载模块,设备节点被创建 卸载模块,节点被注销
网友评论