You are on page 1of 10

NGUYÊN LÝ HỆ ĐIỀU HÀNH

BÀI TẬP CHƯƠNG 2


LINUX KERNEL MODULES

◼ Listing kernel modules


◼ Creating a simple kernel module
◼ Working with modules
◼ Writing the Makefile
◼ Kernel data structures
Listing kernel modules

◼ lsmod

 Hiển thị các modules đang được nạp trong kernel theo 3
cột
 Tên module
 Kích thước
 Được sử dụng ở đâu

Lê Minh Tuấn ©2013


Creating kernel modules

◼ A simple module mymodule.c


#include<linux/init.h>
#include<linux/kernel.h>
#inlude<linux/module.h>

/* This function is called when the module is loaded. */


int mymodule_init(void) // Module entry point
{
printk(KERN_INFO “My module is loaded.\n”);
return 0;
}
/* This function is called when the module is removed. */
void mymodule_exit(void) // Module exit point
{
printk(KERN_INFO “Removing my module.\n”);
}
/* Macros for registering module entry and exit points. */
module_init(mymodule_init);
module_exit(mymodule_exit);

MODULE_LICENSE(“GPL”);
MODULE_DESCRIPTION(“My first kernel module”);
MODULE_AUTHOR(“Le Minh Tuan”); Lê Minh Tuấn ©2013
Working with Modules

◼ Nạp module lên kernel của HĐH


 sudo insmod mymodule.ko

◼ Hiển thị nội dung trong kernel log buffer


 dmesg
◼ Xóa log
 sudo dmesg -c

◼ Gỡ bỏ module từ kernel của HĐH


 sudo rmmod mymodule

Lê Minh Tuấn ©2013


Writing the Makefile
◼ Makefile

obj –m += mymodule.o
KVERSION = $(shell uname –r)
all:
make –C /lib/modules/$(KVERSION)/build M=$(PWD) modules
clean:
make –C /lib/modules/$(KVERSION)/build M=$(PWD) clean

Lê Minh Tuấn ©2013


Kernel Data Structure

◼ Cho cấu trúc dữ liệu


struct birthday{
int day;
int month;
int year;
struct list_head list;
};

◼ Viết module:
 module entry point: tạo một danh sách liên kết chứa 5
phần tử birthday. Duyệt danh sách và hiển thị nội dung
từng phần tử trong kernel log buffer
 module exit point: xóa toàn bộ các phần tử trong danh

sách liên kết, giải phóng bộ nhớ kernel


Lê Minh Tuấn ©2013
Kernel Data Structure

◼ Hướng dẫn
LIST_HEAD(birthday_list);
//Khởi tạo biến danh sách liên kết birthday_list

struct birthday *person;


//Khai báo biến con trỏ kiểu birthday

person = kmalloc(sizeof(*person), GFP_KERNEL);


//Cấp phát bộ nhớ cho con trỏ

Lê Minh Tuấn ©2013


Kernel Data Structure

◼ Hướng dẫn
INIT_LIST_HEAD(&person->list);
//Khởi tạo danh sách rỗng

list_add_tail(&person->list, &birthday_list);
//Thêm phần tử vào danh sách

list_for_each_entry(ptr, &birthday_list, list)


{
//duyệt danh sách liên kết
} Lê Minh Tuấn ©2013
Kernel Data Structure

◼ Thư viện
#include<linux/list.h> //linked list
#include<linux/types.h> //list_head structure

Lê Minh Tuấn ©2013

You might also like