最简单的内核模块hello world

[root@localhost /home/ahao.mah/main]
#cat  hello.c
// Defining __KERNEL__ and MODULE allows us to access kernel-level code not usually available to userspace programs.
#undef __KERNEL__
#define __KERNEL__

#undef MODULE
#define MODULE

// Linux Kernel/LKM headers: module.h is needed by all modules and kernel.h is needed for KERN_INFO.
#include <linux/module.h>    // included for all kernel modules
#include <linux/kernel.h>    // included for KERN_INFO
#include <linux/init.h>        // included for __init and __exit macros

static int __init hello_init(void)
{
    printk(KERN_INFO "Hello world!\n");
    return 0;    // Non-zero return means that the module couldn't be loaded.
}

static void __exit hello_cleanup(void)
{
    printk(KERN_INFO "Cleaning up module.\n");
}

module_init(hello_init);
module_exit(hello_cleanup);
[root@localhost /home/ahao.mah/main]
#cat Makefile
obj-m := hello.o
KDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)

all:
    $(MAKE) -C $(KDIR) M=$(PWD) modules

clean:
    $(MAKE) -C $(KDIR) M=$(PWD) clean
[root@localhost /home/ahao.mah/main]
#ll Makefile hello.c
-rw-r--r-- 1 root root 785 Dec 21 15:48 hello.c
-rwxr-xr-x 1 root root 170 Dec 21 15:51 Makefile
[root@localhost /home/ahao.mah/main]
#make
make -C /lib/modules/3.10.0-327.ali2000.alios7.x86_64/build M=/home/ahao.mah/main modules
make[1]: Entering directory `/usr/src/kernels/3.10.0-327.ali2000.alios7.x86_64'
  CC [M]  /home/ahao.mah/main/hello.o
  Building modules, stage 2.
  MODPOST 1 modules
  CC      /home/ahao.mah/main/hello.mod.o
  LD [M]  /home/ahao.mah/main/hello.ko
make[1]: Leaving directory `/usr/src/kernels/3.10.0-327.ali2000.alios7.x86_64'
[root@localhost /home/ahao.mah/main]
#ls
hello.c  hello.ko  hello.mod.c  hello.mod.o  hello.o  Makefile  modules.order  Module.symvers
[root@localhost /home/ahao.mah/main]
#lsmod  | grep hello

[root@localhost /home/ahao.mah/main]
#insmod hello.ko

[root@localhost /home/ahao.mah/main]
#lsmod  | grep hello
hello                  12428  0
[root@localhost /home/ahao.mah/main]
#tail /var/log/messages
Dec 21 15:52:43 rt2m09617 kernel: hello: module license 'unspecified' taints kernel.
Dec 21 15:52:43 rt2m09617 kernel: Disabling lock debugging due to kernel taint
Dec 21 15:52:43 rt2m09617 kernel: hello: module verification failed: signature and/or required key missing - tainting kernel
Dec 21 15:52:43 rt2m09617 kernel: Hello world!

转载于:https://www.cnblogs.com/muahao/p/6208018.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值