今天記錄一下簡單的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
