针对前面解析的双链表API,本文做一个简单使用实例。正所谓:千言万语,不如举一个好例子!不过,这个例子很简单,没有做安全机制,只是简单的使用,而且是链表的常用API,希望对读者能起到抛砖引玉的作用!
list_module.c
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/slab.h>
static char *str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//定义一个用户数据类型
struct info_struct{
char name[32];
unsigned int age;
struct list_head entry;
};
//双链表表头
static LIST_HEAD(head);
//遍历链表
static void print_list(void)
{
struct info_struct *pos;
struct list_head *list_head = &head;
int i = 0;
list_for_each_entry(pos, list_head, entry)
{
++i;
printk(KERN_INFO"name:%s\tage:%d\n", pos->name, pos->age);
}
printk(KERN_INFO"sum:%d\n", i);
}
//销毁链表
static void destroy_list(void)
{
struct info_struct *pos, *n;
struct list_head *list_head = &head;
list_for_each_entry_safe(pos, n, list_head, entry)
{
list_del(&pos->entry);
kfree(pos);
}
INIT_LIST_HEAD(list_head);
}
static void creat_list(void)
{
//向链表添加元素
int i;
struct info_struct *buff;
for(i = 0; i < 10; ++i)
{
buff = kmalloc(sizeof(struct info_struct), GFP_ATOMIC);
if(!buff)
{
printk(KERN_ALERT"ERROR:kmalloc memory fail!\n");
break;
}
//初始化数据
memcpy(buff->name, str + i, 17);
buff->name[17] = 0;
buff->age = 26 - i;
//放入双链表
list_add(&buff->entry, &head);
}
}
//查找并删除元素
static void search_and_del_entry(unsigned int age)
{
struct info_struct *pos, *n;
list_for_each_entry_safe(pos, n, &head, entry)
{
if(pos->age == age)
{
list_del(&pos->entry);
kfree(pos);
printk(KERN_INFO"age:%d delete!\n", age);
}
}
}
//查找位置并插入之前
static void search_and_insert_entry(unsigned int age, struct info_struct *buff)
{
struct info_struct *pos;
list_for_each_entry(pos, &head, entry)
{
if(pos->age == age)
{
list_add_tail(&buff->entry, &pos->entry);
printk(KERN_INFO"age:%d prev insert an entry!\n", age);
break;
}
}
}
static int __init list_init(void)
{
struct info_struct *buff;
creat_list();
print_list();
search_and_del_entry(18);
print_list();
buff = kmalloc(sizeof(struct info_struct), GFP_ATOMIC);
if(buff)
{
memcpy(buff->name, "Hello List, I'm newer!", 22);
buff->name[22] = 0;
buff->age = 0;
search_and_insert_entry(24, buff);
print_list();
}
printk(KERN_INFO"list_module insert successfully!\n");
return 0;
}
static void __exit list_exit(void)
{
destroy_list();
printk(KERN_INFO"list_module remove successfully!\n");
}
module_init(list_init);
module_exit(list_exit);
MODULE_LICENSE("GPL");
Makefile
ifneq ($(KERNELRELEASE),)
obj-m :=list_module.o
else
KERNELDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
default:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
endif
步骤
make(编译模块)->insmod list_module.ko(root权限添加模块)->dmesg(查看运行结果)->rmmod list_module(root权限卸载模块)over!