1.hello.c

#include<linux/kernel.h>
#include<linux/stat.h>
#include<linux/moduleparam.h>
#include<linux/init.h>
#include<linux/module.h>
static short int a=1;
static int b=2;
static long int c=3;
static char *d="bp";
static int myintArray[2]={-1,-1};
static int arr_argc=0;

module_param(a,short,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP);
MODULE_PARM_DESC(a,"a short integer");
module_param(b,int ,S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
MODULE_PARM_DESC(b,"an integer");
module_param(c,long,S_IRUSR);
MODULE_PARM_DESC(c,"a long integer");
module_param(d,charp,0000);
MODULE_PARM_DESC(d,"a char string");
module_param_array(myintArray,int,&arr_argc,0000);
MODULE_PARM_DESC(myintArray,"an array of integers");
static int __initdata hellodata=3;
static int __init bp_init(void){
    int i;
    printk(KERN_ALERT "hello world\n");
    printk(KERN_ALERT "a is a short integer:%d\n",a);
    printk(KERN_ALERT "b is a integer:%d\n",b);
    printk(KERN_ALERT "c is a long integer:%d\n",c);
    printk(KERN_ALERT "d is a string:%s\n",d);
    for(i=0;i<(sizeof(myintArray)/sizeof(int));i++)
        printk(KERN_ALERT "myintArray[%d] is %d\n",i,myintArray[i]);
    printk(KERN_ALERT   "\nhi,this is bp %d \n",hellodata);
    return 0;
}
static void __exit bp_exit(void){
    printk(KERN_ALERT   "\ngoobye bp\n");
}
//当向内核插入模块时调用init函数
module_init(bp_init);
//从内核删除模块时则调用exit函数。
module_exit(bp_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("by bp");
MODULE_DESCRIPTION("this is test of bp");
MODULE_SUPPORTED_DEVICE("testdevice");

2.Makefile

obj-m := hello.o
server-objs := hello.o

KERNELDIR := /lib/modules/$(shell uname -r)/build

PWD := $(shell pwd)
default:
    $(MAKE) -C  $(KERNELDIR) M=$(PWD) modules 
clean:
    rm -f *.o *.ko *.mod.c modules.* Module.*

3.输入make进行编译
image.png
(没有错误就是正常提示。。)
ls查看是否生成.ko等文件
image.png
4.使用insmod将模块插入内核中,使用方法:#insmod XXX.ko

sudo insmod hello.ko

5.dmesg查看内核输出

dmesg

image.png
6.使用rmmod将模块从内核中删除,使用方法:#rmmod XXX.ko

sudo rmmod hello

image.png
此时程序退出了,使用dmesg查看打印了module_exit方法:
image.png


ch123
60 声望7 粉丝

积土而为山,积水而为海。