编写kernel第一个Hello World

来源:互联网 发布:mysql for python 2.7 编辑:程序博客网 时间:2024/06/05 02:07

原址

目的: 主要用于熟悉驱动程序编写及调试基本流程。

1.准备

         操作系统: ubuntu12.04 LTS

2.源码

[cpp] view plain copy
  1. #include <linux/init.h>  
  2. #include <linux/module.h>  
  3.   
  4. static int hello_init(void)  
  5. {  
  6.     pr_info("Hello, World.\n");  
  7.     return 0;  
  8. }  
  9.   
  10. static void hello_exit(void)  
  11. {  
  12.     pr_info("Goodbye, cruel world\n");  
  13. }  
  14.   
  15. module_init(hello_init);  
  16. module_exit(hello_exit);  
  17.   
  18. MODULE_LICENSE("Dual BSD/GPL");  

3.Makefile

[plain] view plain copy
  1. obj-m := hello.o  
  2.   
  3. KERNELDIR := /usr/src/linux-headers-$(shell uname -r)  
  4. PWD := $(shell pwd)  
  5.   
  6. modules:  
  7.     $(MAKE) -C $(KERNELDIR) M=$(PWD) modules  
  8. modules_install:  
  9.     $(MAKE) -C $(KERNELDIR) M=$(PWD) modules_install  

4.编译

make:
[plain] view plain copy
  1. ckt@ubuntu:~/work/ldd/hello$ make  
  2. make -C /usr/src/linux-headers-3.13.0-32-genericM=/home/ckt/work/ldd/hello modules  
  3. make[1]: Entering directory`/usr/src/linux-headers-3.13.0-32-generic'  
  4.   CC [M]  /home/ckt/work/ldd/hello/hello.o  
  5.   Buildingmodules, stage 2.  
  6.   MODPOST 1modules  
  7.   LD [M]  /home/ckt/work/ldd/hello/hello.ko  
  8. make[1]: Leaving directory`/usr/src/linux-headers-3.13.0-32-generic'  

5.测试

[plain] view plain copy
  1. lsmod                  #查看当前加载的模块  
  2. sudo insmod hello.ko         #加载hello.ko模块  
  3. sudo rmmod hello             #移除hello.ko模块  
  4. cat/var/log/syslog     #查看日志  

原创粉丝点击