簡單的Linux驅動程序以及如何加載/卸載驅動


今天記錄一下簡單的Linux驅動程序怎么寫以及如何加載/卸載驅動

hello.c為例:

hello.c

 

#ifndef __KERNEL__
#  define __KERNEL__
#endif
#ifndef MODULE
#  define MODULE
#endif

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

static int hello_init(void){
    printk(KERN_ALERT "HELLO WORLD\n");
    return 0;
}
static void hello_exit(void){
    printk(KERN_ALERT "GOODBYE CRUEL WORLD\n");
}
module_init(hello_init);
module_exit(hello_exit);

/*
3.5.0-23-generic
make -C /lib/modules/3.5.0-23-generic/build M=`pwd` modules
*/

  

Makefile來編譯:

Makefile

obj-m := hello.o

all :
    $(MAKE) -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

clean:
    $(MAKE) -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

 

以下終端是編譯命令,下圖所示編譯成功:

加載和移除驅動:

sudo insmod ./hello.ko
sudo rmmod hello       

  

查看日志

tail /var/log/kern.log 

參考博客https://www.cnblogs.com/QuLory/archive/2012/10/23/2736339.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM