操作系统学习入门1

内核模块编程入门:

一、准备工作:

  1、打开一个终端,输入命令:

    $ uname -r
    结果:5.5.2-1-MANJARO

  2、安装必要的内核文件:

    sudo pacman -S linux55-headers

    正在解析依赖关系...
    正在查找软件包冲突...

    软件包 (1) linux55-headers-5.5.2-1

    全部安装大小: 47.53 MiB
    净更新大小: 47.53 MiB

    :: 进行安装吗? [Y/n]  

    按下回车,安装

  3、准备代码目录:

    mkdir  -p  drivers/hello

    cd  drivers/hello

二、编辑源代码和make文件:

  1、使用vim编辑源码hello.c

 1 #include 
 2 #include 
 3 
 4 static char *name = "guochao";
 5 static int count = 5;
 6 
 7 module_param(name, charp, S_IRUGO);
 8 module_param(count, int, S_IRUGO);
 9 
10 static int hello_init(void){
11     int i = 0;
12     for(i = 0; i < count; i++){
13         printk(KERN_INFO"Hello %d, %s! This is start%d\n", i, name, i);
14     }
15     return 0;
16 }
17 
18 static void hello_exit(void){
19     int i = count;
20     for(i = count; i > 0; i--){
21         printk(KERN_INFO "Hello %d, %s! This is exit %d\n", i, name, i);
22     }
23 }
24 
25 MODULE_LICENSE("GPL");
26 module_init(hello_init);
27 module_exit(hello_exit);

  代码比较简单,不多说明

Makefile文件为:

 1 KVERS=$(shell uname -r)
 2 #kernel modules
 3 obj-m +=hello.o
 4 
 5 #Specif flags for the module compilation.
 6 #EXTRA_CFLAGS=-g -O0
 7 
 8 buile:kernel_modules
 9 
10 kernel_modules:
11     make -C  /lib/modules/$(KVERS)/build M=$(CURDIR) modules
12 
13 clean:
14     make -C  /lib/modules/$(KVERS)/build M=$(CURDIR) clean

目录下文件为:

  $ ls
  hello.c  Makefile

三、模块的处理

  0、编译模块  

  $ make
  make -C /lib/modules/5.5.2-1-MANJARO/build M=/home/nication/drivers/hello modules
  make[1]: 进入目录“/usr/lib/modules/5.5.2-1-MANJARO/build”
    CC [M] /home/nication/drivers/hello/hello.o
    Building modules, stage 2.
    MODPOST 1 modules
    CC [M] /home/nication/drivers/hello/hello.mod.o
    LD [M] /home/nication/drivers/hello/hello.ko
  make[1]: 离开目录“/usr/lib/modules/5.5.2-1-MANJARO/build”

  make后的文件如下:

  $ ls
  hello.c  hello.ko  hello.mod  hello.mod.c  hello.mod.o  hello.o  Makefile  modules.order  Module.symvers

  以下操作用root用户:

  1、加载模块

  # insmod hello.ko                           //加载模块

  # lsmod | grep hello                       //查看加载的模块

  hello                  16384  0  

  # dmesg | grep Hello                     //查看模块的输出信息
  [11817.505058] Hello 0, guochao! This is start0
  [11817.505062] Hello 1, guochao! This is start1
  [11817.505064] Hello 2, guochao! This is start2
  [11817.505066] Hello 3, guochao! This is start3
  [11817.505068] Hello 4, guochao! This is start4 

  2、卸载模块

  # rmmod hello                                //卸载模块

  # lsmod | grep hello                       //查看加载的模块

  # dmesg | grep Hello                     //查看模块的输出信息 

  [12466.702875] Hello 5, guochao! This is exit 5
  [12466.702880] Hello 4, guochao! This is exit 4
  [12466.702882] Hello 3, guochao! This is exit 3
  [12466.702884] Hello 2, guochao! This is exit 2
  [12466.702885] Hello 1, guochao! This is exit 1

  3、清除无用代码:

  make clean
   

  

 

你可能感兴趣的:(操作系统学习入门1)