好记性不如铅笔头

C && C++, kernel, linux, 操作系统, 编程

驱动学习笔记:HelloWorld

最近突然想重新学习驱动开发,在ubuntu上装好SSH之后,环境基本上就OK了,那么就先写一个最基础的helloworld。

为了方便,先切换到root:

cstriker1407@cstriker1407-ubuntu:~$ sudo passwd
[sudo] password for cstriker1407: 
输入新的 UNIX 密码: 
重新输入新的 UNIX 密码: 
passwd:已成功更新密码
cstriker1407@cstriker1407-ubuntu:~$ su - 
密码: 
root@cstriker1407-ubuntu:~# mkdir helloworld
root@cstriker1407-ubuntu:~# cd helloworld/

然后新建两个文件:

【 helloworld.c 】

#include <linux/kernel.h>
#include <linux/module.h>

MODULE_LICENSE("Dual BSD/GPL");

static int __init hello_init(void)
{
	printk(KERN_ALERT "Hello world\n");
	return 0;
}

static void __exit hello_exit(void)
{
	printk(KERN_ALERT "Goodbye world\n");
}

module_init(hello_init);
module_exit(hello_exit);

【 Makefile 】

obj-m := helloworld.o
KERNEL_DIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
all:
	make -C $(KERNEL_DIR) SUBDIRS=$(PWD) modules
clean:
	rm *.o *.ko *.mod.c

.PHONY:clean

然后就可以编译了,命令记录如下:

root@cstriker1407-ubuntu:~/helloworld# ls
helloworld.c  Makefile
root@cstriker1407-ubuntu:~/helloworld# make
make -C /lib/modules/3.11.0-15-generic/build SUBDIRS=/root/helloworld modules
make[1]: 正在进入目录 `/usr/src/linux-headers-3.11.0-15-generic'
  CC [M]  /root/helloworld/helloworld.o
  Building modules, stage 2.
  MODPOST 1 modules
  CC      /root/helloworld/helloworld.mod.o
  LD [M]  /root/helloworld/helloworld.ko
make[1]:正在离开目录 `/usr/src/linux-headers-3.11.0-15-generic'
root@cstriker1407-ubuntu:~/helloworld# ls
helloworld.c  helloworld.ko  helloworld.mod.c  helloworld.mod.o  helloworld.o  Makefile  modules.order  Module.symvers

载入模块和卸载模块:

root@cstriker1407-ubuntu:~/helloworld# insmod helloworld.ko
root@cstriker1407-ubuntu:~/helloworld# rmmod helloworld.ko

此时,应该会有日志打印到终端,如下图:

如果不好关注终端,也可以手动查看日志显示,可用下面的两个命令:

 dmesg | tail
 tail -f /var/log/kern.log 

 

发表评论

5 × 5 =

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据