操作系统(龙书)第二章内核模块项目报告

本文介绍了如何在Linux系统中创建、加载和卸载内核模块,包括编写`simple.c`文件、使用`insmod`加载模块、验证输出以及处理内存管理。还展示了如何创建`birthday`结构体并在模块加载和退出时操作链表。
摘要由CSDN通过智能技术生成

Linux内核模块

在这一部分中,我学会了如何创建,加载与卸载内核模块,首先根据书上的代码编写好simple.c文件和Makefile文件,接着使用make编译,产生如下文件:

接着使用加载模块命令:sudo insmod simple.ko 将simple模块加载,并使用lsmod检查确定simple已经被加载:

       使用dmesg命令检查模块中的“Loading Module”消息是否被输出。

       使用命令sudo rmmod simple删除刚刚加载的模块并检查日志缓冲区:

       及时使用sudo dmesg -c命令清理缓冲区:

第二部分

       创建birthday结构体并创建第一个元素将其内容输出到内核日志缓冲区中。

       添加其他的四个元素并使用list_for_each_entry()输出:

       在模块退出时,删除链表元素,并返回之前分配的内存,以防止内存泄漏。其中使用list_empty()函数判断是否将链表元素删除。

源代码如下

#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/list.h>
#include <linux/types.h>
#include <linux/slab.h>


typedef struct birthday{
	int day;
	int month;
	int year;
	struct list_head list;
}birthday;
static LIST_HEAD(birthday_list);

/*This function is called to create a new node*/
birthday* list_cret(int day,int month,int year)
{

	//printk("The list_cret function has been used.");
	struct birthday *person;
	person=kmalloc(sizeof(*person),GFP_KERNEL);
	person->day=day;
	person->month=month;
	person->year=year;
	INIT_LIST_HEAD(&person->list);

	return person;
}

/*This function is called when the module is loaded.*/
int simple_init(void)
{
	printk(KERN_INFO "Loading Module\n");

	//test for list
	birthday *p1=list_cret(2,8,1995);
	list_add_tail(&p1->list,&birthday_list);//add to the list

	birthday *p2=list_cret(3,9,1996);
        list_add_tail(&p2->list,&birthday_list);//add to the list

	birthday *p3=list_cret(4,10,1997);
        list_add_tail(&p3->list,&birthday_list);//add to the list

	birthday *p4=list_cret(5,11,1998);
        list_add_tail(&p4->list,&birthday_list);//add to the list

	birthday *p5=list_cret(6,12,1999);
        list_add_tail(&p5->list,&birthday_list);//add to the list

	//Traversal list
	struct birthday *ptr;
	list_for_each_entry(ptr,&birthday_list,list){
		printk(KERN_INFO "%d--%d--%d\n",ptr->year,ptr->month,ptr->day);
	}

	return 0;
}

/*This function is called when the module is removed.*/
void simple_exit(void)
{
	printk(KERN_INFO "Removing Module\n");

	//delete the list node
	struct birthday *ptr,*next;
	list_for_each_entry_safe(ptr,next,&birthday_list,list){
		list_del(&ptr->list);
		kfree(ptr);//free the memeory
	}
	//the list is empty,the action is success
	if(list_empty(&birthday_list)) printk(KERN_INFO "delete success\n");
}

/*Macros for registering module entry and exit points.*/
module_init(simple_init);
module_exit(simple_exit);

MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Simple Module");
MODULE_AUTHOR("SGG");

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值