Linux系統內核模塊和驅動的編寫 (2)
發表于:2007-05-26來源:作者:點擊數:
標簽:
這樣一個例子就完成了.我們也寫一個makefile的例子,以適于我們在大程序重的應用。一下是makfile文件的內容。 # a makefile for a module CC=gcc MODCFLAGS:= -Wall _DMODULE -D_KERNEL_ -DLinux hello.o hello.c /usr/inculde?Linux/version.h CC $(MODCFLA
這樣一個例子就完成了.我們也寫一個makefile 的例子,以適于我們在大程序重的應用。一下是makfile 文件的內容 。
# a makefile for a module
CC=gcc
MODCFLAGS:= -Wall _DMODULE -D_KERNEL_ -DLinux
hello.o hello.c /usr/inculde?Linux/version.h
CC $(MODCFLAGS) 0c hello.c
echo the module is complie completely
|
然后你運行make 命令 得到hello.o 這個模塊,運行
$insmod hello.o
hello world!
I will shut down myself in kernerl mod
$lsmod
hello (unused)
….
$remmod
I will shut down myself in kernerl mod
|
這樣你的模塊就可以隨意的插入和刪除了。
Linux中的大部分驅動程序,是以模塊的形式編寫的,這些驅動程序源碼可以修改到內核中,也可以把他們編譯成模塊形勢,在需要的時候動態加載。
一個典型的驅動程序,大體上可以分為這么幾個部分:
1.注冊設備
在系統初啟,或者模塊加載時候,必須將設備登記到相應的設備數組,并返回設備的主驅動號,例如:對快設備來說調用 refister_blkdec()將設備添加到數組blkdev中,并且獲得該設備號,并利用這些設備號對此數組進行索引。對于字符驅動設備來說,要使用 module_register_chrdev()來獲得祝設備的驅動號,然后對這個設備的所有調用都用這個設備號來實現。
2.定義功能函數
對于每一個驅動函數來說,都有一些和此設備密切相關的功能函數,那最常用的塊設備或者字符設備來說,都存在著諸如 open() read() write() ioctrol()這一類的操作。當系統社用這些調用時,將自動的使用驅動函數中特定的模塊,來實現具體的操作。而對于特定的設備,上面的系統調用對應的函數是一定的。
如:在塊驅動設備中.當系統試圖讀取這個設備(即調用read()時),就會運行驅動程序中的block_read() 這個函數。
打開新設備時會調用這個設備驅動程序的device_open() 這個函數.
3.謝載模塊
在不用這個設備時,可以將他卸載,主要是從/proc 中取消這個設備的特殊文件,可用特定的函數實現。
下面我們列舉一個字符設備驅動程序的框架.來說明這個過程.
/* a module of a character device */
/* some include files*/
#include"param.h"
#include"user.h"
#include"tty.h"
#include"dir.h"
#include”fs.h"
/* the include files modules need*/
#include"Linux/kernel.h"
#include"Linux/module.h"
#if CONFIG_MODBERSIONS==1
degine MODBERSIONS
#include" Linux.modversions.h"
#endif
#difine devicename mydevice
/* the init funcion*/
int init_module()
{
int tag=module_register_chrdev(0,mydevice,&Fops);
if (tag<0)
{
printk("the device init is erro!\n");
return 1;
}
return 0;
}
/*the funcion which the device will be used */
int device_open ()
{
…….
}
int device_read ()
{
…….
}
int device_write ()
{
…….
}
int device_ioctl ()
{
…….
}
……
/* the deltter function of this module*/
int cleanup_module()
{
int re=module_unregister_chrdev(tag,mydevice);
if( re<0)
{
printk("erro unregister the module !!\n");
return 1;
}
return 0;
}
|
原文轉自:http://www.kjueaiud.com
老湿亚洲永久精品ww47香蕉图片_日韩欧美中文字幕北美法律_国产AV永久无码天堂影院_久久婷婷综合色丁香五月
|