zoukankan      html  css  js  c++  java
  • 一个简单的内核模块编程实例

    学习netfilter的使用,需要用到模块编程,所以先学习写个模块的例子。

    #include <linux/init.h>
    #include <linux/module.h>
    #include <linux/kernel.h>
    
    static int __init hello_init(void)
    {
        printk(KERN_INFO "call hello_init\n");
        return 0;
    }
    
    static void __exit hello_exit(void)
    {
        printk(KERN_INFO "call hello_exit\n");
    }
    
    module_init(hello_init);
    module_exit(hello_exit);
    
    MODULE_AUTHOR("tonybuaa");
    MODULE_LICENSE("Dual BSD/GPL");
    MODULE_DESCRIPTION("hello module");
    MODULE_ALIAS("a smiplest module");

    Makefile文件是这样的:

    ifeq ($(KERNELRELEASE),)
    KERNELDIR := /lib/modules/$(shell uname -r)/build
    PWD := $(shell pwd)
    default:
        $(MAKE) -C $(KERNELDIR) M=$(PWD) modules
    clean:
        rm -rf *.o *.mod.c *.ko modules.order Module.symvers
    else
        obj-m := hello.o
    endif

    执行make:

    tony@ubuntu-a:~/code/module_test$ make
    make -C /lib/modules/3.8.0-19-generic/build M=/home/tony/code/module_test modules
    make[1]: 正在进入目录 `/usr/src/linux-headers-3.8.0-19-generic'
      CC [M]  /home/tony/code/module_test/hello.o
      Building modules, stage 2.
      MODPOST 1 modules
      CC      /home/tony/code/module_test/hello.mod.o
      LD [M]  /home/tony/code/module_test/hello.ko
    make[1]:正在离开目录 `/usr/src/linux-headers-3.8.0-19-generic'

    安装内核模块:

    tony@ubuntu-a:~/code/module_test$ sudo insmod ./hello.ko

    使用dmesg | tail查看内核日志打印信息:

    tony@ubuntu-a:~/code/module_test$ dmesg | tail
    [13270.772001] call hello_init

    卸载内核模块:

    tony@ubuntu-a:~/code/module_test$ sudo rmmod hello

    再次查看内核日志:

    tony@ubuntu-a:~/code/module_test$ dmesg | tail
    [13270.772001] call hello_init
    [13337.794110] call hello_exit
  • 相关阅读:
    BZOJ4407
    BZOJ 4804
    BZOJ 2820
    莫比乌斯反演入门
    BZOJ3261
    BZOJ 4327
    BZOJ1212
    AC自动机 板子
    派生类的访问控制-“三看”原则-派生类类成员访问级别设置的原则
    为什么不要重载 && 和 || 操作符!!!
  • 原文地址:https://www.cnblogs.com/tonybuaa/p/3052107.html
Copyright © 2011-2022 走看看