linux內核模塊安裝hello

首先編寫內核模塊源碼

#include<linux/init.h>
#include<linux/module.h>
MODULE_LICENSE("GPL");

static int hello_init(void)
{
        printk("<0>hello brother\n");                //<0>表示打印的優先級,一共有8個好像
        return 0;

}
static void hello_exit(void)
{
        printk("<0>good bye\n");

}
module_init(hello_init);
module_exit(hello_exit);

然後編寫makefile

ifneq ($(KERNELRELEASE),)
obj-m:=hello.o                                     //obj-m表示將該文件作爲模塊編譯

else

KDIR:=/lib/modules/2.6.18-194.el5/build
all:
        make -C $(KDIR) M=$(PWD) modules
clean:
        rm -f *.ko *.o *.mod.o *.mod.c *.symvers
endif
然後再執行make編譯hello.c

最後執行insmod ./hello.ko                                 //insmod要在root權限下執行,因爲insmod在/sbin/目錄下,只有root用戶纔有的環境變量

rmmod hello


//-------------------------------------------------------------------------------------------------------------------------------------

多文件

首先編寫內核模塊源碼

#include<linux/init.h>
#include<linux/module.h>
MODULE_LICENSE("GPL");
extern int add(int a,int b);
static int hello_init(void)
{
	int i=0;
        printk("<0>hello brother\n");                //<0>表示打印的優先級,一共有8個好像
	i=add(4,5);
	printk(KERN_EMERG"%d",i);
        return 0;

}
static void hello_exit(void)
{
        printk("<0>good bye\n");

}
module_init(hello_init);
module_exit(hello_exit);

add函數

int add(int a,int b)
{
	return a+b;
}


然後編寫makefile

ifneq ($(KERNELRELEASE),)
obj-m:=hp.o                 //hp.o模塊
hp-objs:=hello.o add.o      //hp模塊所依賴的文件
else

KDIR:=/lib/modules/2.6.18-194.el5/build
all:
        make -C $(KDIR) M=$(PWD) modules
clean:
        rm -f *.ko *.o *.mod.o *.mod.c *.symvers
endif



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章