Linux--写一个简单的模块

1.创建一个目录#mkdir zhu  

#cd zhu  

#vim hello.c 编写一个名为hello的文件  

2.hello.c:

#include <linux/module.h> //所有模块都需要的头文件

#include <linux/init.h>

static int hello_init(void)

{  

printk(KERN_ERR "hello world");  

return 0;

}

static void hello_exit(){  

printk(KERN_EMERG "hello exit!");

}

module_init(hello_init);

module_exit(hello_exit)


3.#vim makefile 写makefile文件

Makefile:

  1.       
  2. ifneq ($(KERNELRELEASE),)
  3. obj-:=hello.o
  4. else
  5. KDIR :=/lib/modules/$(shell uname -r)/build
  6. all:
  7. make -C $(KDIR) M=$(PWD) modules
  8. clean:
  9. rm -*.ko *.*.mod.*.mod.*.symvers
  10. endif

注意: 书写Makefile文件时命令行前要按【Tab】键


4.#make 编译模块

5.出错1:“/root/zhu/Makefile: no such file or directory ” 是因为makefile 未大写成Makefile

## mv makefile Makefile

出错2:“syntax error near unexpected token '/build' ” 是因为附近有语法错误,最后知道是一个符号写错。


6.重新修改代码后make 成功。生成hello.ko

7.#insmod hello.ko 加载模块

#lsmod | grep hello

hello 12496 0


8.模块的代码是在内核中运行的,所以必须要看内核缓冲区控制信息

  #dmesg 来查看具体模块代码运行情况


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值