llinux 驱动程序开发-Hello world.c
如何编写一个Helloworld 模块并且编译后加入到kernel,以下code在linux采用 vi 编辑器书写
// hello.c
//author: Mingzhou
#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,see you again!\n”);
}
module_init(hello_init);
module_exit(hello_exit);
hello.c 的Makefile
obj-m =hello.o
KERNELTOP=/lib/modules/
(
s
h
e
l
l
u
n
a
m
e
−
r
)
K
E
R
N
E
L
D
I
R
=
(shell uname -r) KERNELDIR=
(shelluname−r)KERNELDIR=(KERNELTOP)/build
PWD=$(shell pwd)
modules:
$(MAKE) -C
(
K
E
R
N
E
L
D
I
R
)
M
=
(KERNELDIR) M=
(KERNELDIR)M=(PWD) modules
modules_install:
$(MAKE) -C
(
K
E
R
N
E
L
D
I
R
)
M
=
(KERNELDIR) M=
(KERNELDIR)M=(PWD) modules_install
保存退出后,在root权限下执行make。
- linux驱动程序编译成功后可以使用linux下的shell 命令insmod hello.ko 将编译后的驱动模块动态加载到kernel中(需要在root模式下进行)。
- 可以通过lsmod 或者dmesg | tail 查看加载到kernel的hello 模块。
- 通过rmmod hello 将hello 模块从kernel中移除。