2016-03-16

CentOS 7 : Kernel 3.14 : HelloWorld Module 빌드하기.

CentOS 7 : Kernel 3.14 : HelloWorld Module 빌드하기.
아주 간단한 리눅스 커널 모듈을 만들어 보자.
목표는 모듈 등록과 삭제후 “dmseg | tail”  명령으로 메세지를 확이 할수 있게 하는것이다.

  1. 먼저 커널 모듈을 작성한다.
임의의 디렉토리 “/roor/Desktop/helloworld”에 모듈 소스를 작성한다.

helloworld.c
#include <linux/module.h>
#include <linux/init.h>

static int __init helloworld_init(void)
{
   pr_info("Hello World!\n");
   return 0;
}

static void __exit helloworld_exit(void)
{
   pr_info("Goodby World.\n");
}

module_init(helloworld_init);
module_exit(helloworld_exit);
MODULE_AUTHOR("root");
MODULE_DESCRIPTION("Hello World Module");

※  기타 MODULE_XXXX
: modinfo 명령으로 해당 모듈을 조회시 표현되는 정보들을 등록 한다.
modinfo_list.PNG

※   커널 시스템 메세지 출력
pr_info("Hello World!\n");
을 사용하거나

incude<kernel.h>
printk(“Hello World!\n");
을 사용한다.

    

  1. 커널 모듈을 빌드하기 위한 Makefile 작성

Makefile
KERNEL_DIR := /lib/modules/`uname -r`/build
BUILD_DIR := `pwd`
VERBOSE   := 1

obj-m := helloworld.o

all:
make -C $(KERNEL_DIR) SUBDIRS=$(BUILD_DIR) KBUILD_VERBOSE=$(VERBOSE) modules

clean:
rm -rf  *.o *.ko *.mod.c *.symvers *.order .tmp_versions .helloworld.c.*

※  Makefile 필수 문법.
: Makefile 에서 사용하는 시스템 명령어는 반드시 {TAB}으로 띄어져 있어야 한다.

  1. 커널 모듈을 작성 한다.
# make
make -C /lib/modules/3.14.64/build SUBDIRS=/root/drivers KBUILD_VERBOSE=0 modules
make[1]: Entering directory `/usr/src/kernels/3.14.64'
 CC [M]  /root/drivers/helloworld.o
 Building modules, stage 2.
 MODPOST 1 modules
 CC      /root/drivers/helloworld.mod.o
 LD [M]  /root/drivers/helloworld.ko
make[1]: Leaving directory `/usr/src/kernels/3.14.64'
# ls
helloworld.c   helloworld.mod.c  helloworld.o  Makefile~      Module.symvers
helloworld.ko  helloworld.mod.o  Makefile      modules.order

※  Makefile 디버깅
: maked -d 로 실행 하면 자세한 상황을 확인 할수 있다.
  1. 동작확인

  • 모듈을 커널에 등록.
# insmod helloworld.ko
# echo $?
0

  • 커널에 로드된 모듈을 조회
# lsmod | grep helloworld
helloworld             12430  0

< 모듈 이름>         <모듈이 사용하는 메모리 사이즈 > < 해당 모듈을 참조하는 모듈의 수>

  • 커널 모듈 파일의 정보 조회
# modinfo helloworld.ko
filename:       /root/workspace/drivers/src/helloworld.ko
license:        BSD
description:    Hello World Module
author:         root
srcversion:     EB07C4DCC99CCF81F69125E
depends:        
vermagic:       3.14.64 SMP mod_unload modversions

  • 커널에서 로드된 모듈 삭제
# rmmod helloworld
# echo $?
0

  • 커널 정상 동작 확인
# dmesg | tail
[ 7921.789879] Hello World!
[ 7983.689416] Goodby World.

No comments:

Post a Comment