Tuesday, April 21, 2015

Module Programming

@ Module Programming
  : Module은 "Kernel 계층에서 실행되는 작은 프로그램 단위" 임
  : 장점은 Kernel 동작 중인 Runtime에 동적으로 insert, remove가 가능함
  : System call 추가와 같이 매번 Kernel Rebuild가 필요하다면 매우 비효율적임

  : Module은 개발자들에게 편리한 기능으로, end-user에게는 필요가 없음
  : 그래서 개발이 완료되면 보통 Kernel에 build-in 하여 사용함

@ Version magic
  : Build된 Kernel과 Module을 build하는 kernel이 다르다면 insmod에 실패할 수 있음
  : 왜냐하면 Module이 사용하는 API가 현재 Kernel과 불일치할 수 있기 때문임
  : Module을 사용할 때는 항상 이 부분을 체크해야 함

/*
 * hello_module.c
 */
#include <linux/init.h>
#include <linux/module.h>

static int hello_init(void)
{
    printk("Hello,Linux World!!\n");

    return 0;
}

static void hello_exit(void)
{
    printk("Goodbye,Cruel World!!\n");
}

module_init(hello_init); // insmod 명령 시 수행되는 함수
module_exit(hello_exit); // rmmod 명령 시 수행되는 함수

MODULE_LICENSE("GPL");


/*
 * Makefile
 */
obj-m  := hello_module.o

KDIR  := /root/elayer/EmbeddedLinuxSystem/linux/kernel/linux-2.6.24-el2440-0504-final

PWD    := $(shell pwd)

default:
$(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules
clean :
rm -rf *.ko
rm -rf *.mod.*
rm -rf .*.cmd
rm -rf *.o


/*
 * hello_module.ko 파일 생성
 */
# make
  ...
  CC [M]  /root/hello_module/hello_module.o
  Building modules, stage 2.
  MODPOST 1 modules
  CC      /root/hello_module/hello_module.mod.o
  LD [M]  /root/hello_module/hello_module.ko
  ...


in Target Board,
$ insmod hello_module.ko
Hello, Module!

$ lsmod
Module                  Size  Used by    Not tainted
hello_module            1088  0          0xbf000000

$ rmmod hello_module.ko
Goodbye, Module!

No comments:

Post a Comment