linux內核模塊的編寫

之前學了內核模塊的編寫,但是沒有動手實驗,這次試驗才發現還是有好動東西需要學習!

我的環境是虛擬機跑centos 7 

1.首先編寫模塊:

#include<linux/init.h>
#include<linux/module.h>
MODULE_LICENSE("Dual BSD/GPL");
static int hello_init(void)
{
        printk(KERN_ALERT " Hello World enter\n");
        return 0;
}
static void hello_exit(void)
{
module_exit(hello_exit);
        printk(KERN_ALERT " Hello World exit\n");
}

module_init(hello_init);
MODULE_ALIAS("a simplest module");
MODULE_DESCRIPTION("A simple Hello World Module");


 這裏就不做解釋了,代碼具體可以看我 關於設備驅動的學習:http://blog.csdn.net/u012510450/article/details/78141453

2.編寫Makefile 文件,因爲我還沒有學,所以網絡上copy 別人的,目前只是看得懂。

ifneq ($(KERNELRELEASE),)
 #kbuild syntax. dependency relationshsip of files and target modules are listed here.
mymodule-objs := hello.o
obj-m := hello.o
else
PWD  := $(shell pwd)
        $(MAKE) -C $(KDIR) M=$(PWD) 
KVER ?= $(shell uname -r)
KDIR := /lib/modules/$(KVER)/build
all:
clean:
endif
        rm -rf .*.cmd *.o *.mod.c *.ko .tmp_versions


這裏要注意的是兩點,否則可能報錯【Makefile missing separator. Stop】

a.  ifneq 後面要有一個空格

b.  all,clean 後一行的指令前面要加tab


3.保存後make一下

 這時候我的錯誤提示:linux/module.h: No such file or directory

這是缺少內核頭文件:安裝一下,sudo yum install kernel-headers

其他安裝教程在:http://blog.csdn.net/u012510450/article/details/78141522

然後就ok了


4.運行模塊

 sudo insmod hello.ko

  查看系統

          dmesg

          或者使用lsmod (查看所有模塊)

          我用的是 lsmod | grep ‘hello’

  移除模塊

       sudo rmmod hello


好噠,大功告成,開薰,中間好幾次報錯,主要makefile不會寫,接下來要學好Makefile

 

參考:

http://blog.csdn.net/pottichu/article/details/1892245

http://blog.csdn.net/l_in12/article/details/49640833

http://blog.csdn.net/zaijzhgh/article/details/29918721



1.


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