Linux设备驱动程序第一个例子:Hello World
一、源代码(hello.c 、Makefile)
hello.c:
#include <linux/init.h>
#include <linux/module.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,world\n");
}
module_init(hello_init);
module_exit(hello_exit);
Makefile:
obj-m := hello.o
KERNELDR := /usr/src/linux-headers-$(shell uname -r)
# /usr/src/linux-source-4.4.0,上面是你的内核源码的目录,自己到/usr/src下看一下
PWD := $(shell pwd)
modules:
$(MAKE) -C $(KERNELDR) M=$(PWD) modules
moduels_install:
$(MAKE) -C $(KERNELDR) M=$(PWD) modules_install
clean:
rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versions
1.直接make:(可能会出现以下错误)
错误一:ERROR: Kernel configuration is invalid.include/generated/autoconf.h or include/config/auto.conf are missing.Run 'make oldconfig && make prepare' on kernel src to fix it.
>>>解决方案:点击打开链接
2.加载与卸载驱动模块:
加载:insmod ./hello.ko
卸载:rmmod hello
注意:终端上并不显示输出,用命令【dmesg |tail -10,查看最后10条信息】就能查看输出的Hello,world!
至此,你已经完成了一个最简单的驱动程序!