简单的Linux驱动程序以及如何加载/卸载驱动

今天记录一下简单的Linux驱动程序怎么写以及如何加载/卸载驱动html

hello.c为例:linux

hello.cshell

 

#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来编译:ui

Makefilespa

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

 

如下终端是编译命令,下图所示编译成功:日志

加载和移除驱动:code

sudo insmod ./hello.ko
sudo rmmod hello       

  

查看日志htm

tail /var/log/kern.log 

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