乐趣区

关于linux:Linux内核编程helloworld代码演示

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 进行编译

(没有谬误就是失常提醒。。)
ls 查看是否生成.ko 等文件

4. 应用 insmod 将模块插入内核中,应用办法:#insmod XXX.ko

sudo insmod hello.ko

5.dmesg 查看内核输入

dmesg


6. 应用 rmmod 将模块从内核中删除,应用办法:#rmmod XXX.ko

sudo rmmod hello


此时程序退出了,应用 dmesg 查看打印了 module_exit 办法:

退出移动版