您的位置:首页 > 运维架构 > Linux

Linux 内核模块 helloworld

2017-07-22 20:49 239 查看
uname -r

3.10.0-229.el7.x86_64

hello.c

#ifndef __KERNEL__

# define __KERNEL__

#endif

#ifndef MODULE

# define MODULE

#endif

#include <linux/kernel.h>

#include <linux/module.h>

#include <linux/init.h>

MODULE_LICENSE("GPL");

static int year=2017;

//MODULE_PARM(year,"i");

static int hello_init()

{

printk(KERN_INFO"Hello World %d!\n",year);

return 0;

}

static void hello_exit()

{

printk("Hello Exit!\n");

}

module_init(hello_init);

module_exit(hello_exit);

Makefile

obj-m := hello.o

obj-m2 := hello.ko

all :
$(MAKE) -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

#install :

#insmod $(obj-m2)

#uninstall :

#rmmod $(obj-m2)

.PHONY : clean

clear :
$(MAKE) -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

$(MAKE) 前面是tab

执行 make

make -C /lib/modules/3.10.0-229.el7.x86_64/build M=/root/data/hello modules

make[1]: 进入目录“/usr/src/kernels/3.10.0-229.el7.x86_64”

  CC [M]  /root/data/hello/hello.o

/root/data/hello/hello.c:17:12: 警告:函数声明不是一个原型 [-Wstrict-prototypes]

 static int hello_init()

            ^

/root/data/hello/hello.c:22:13: 警告:函数声明不是一个原型 [-Wstrict-prototypes]

 static void hello_exit()

             ^

  Building modules, stage 2.

  MODPOST 1 modules

  CC      /root/data/hello/hello.mod.o

  LD [M]  /root/data/hello/hello.ko

make[1]: 离开目录“/usr/src/kernels/3.10.0-229.el7.x86_64”

验证:

[root@yujian hello]# insmod ./hello.ko 

[root@yujian hello]# rmmod ./hello.ko 

查看 dmesg 或者 tail -f /var/log/messages

[3722302.058948] Hello World 2017!

[3722324.017678] Hello Exit!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: