#include <linux/init.h>
#include <linux/module.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <linux/kernel.h>
struct list_head head;
struct student
{
int num;
char name[30];
struct list_head list;
};
static int __init listtest_init(void)
{
INIT_LIST_HEAD(&head);
struct student *node_p = NULL;
int i;
//链表的创建
for(i=0; i<10; i++)
{
node_p = kmalloc(sizeof(struct student),GFP_KERNEL);
if(IS_ERR(node_p))
{
goto fail_malloc;
}
node_p->num = i;
sprintf(node_p->name,"studentname%d",i);
list_add(&(node_p->list),&head);
}
//遍历链表
struct list_head *tmp = NULL;
list_for_each(tmp,&head)
{
node_p = list_entry(tmp,struct student,list);
printk("student num: %d \t name: %s\n",node_p->num,node_p->name);
}
#if 0
list_for_each_entry(onep,&head,list)
{
printk("student num: %d \t name: %s\n",onep->num,onep->name);
}
#endif
struct list_head *next_p;
list_for_each_safe(tmp,next_p,&head)
{
node_p = list_entry(tmp,struct student,list);
if(node_p->num == 6)
{
list_del(&node_p->list);
kfree(node_p);
}
}
list_for_each(tmp,&head)
{
node_p = list_entry(tmp,struct student,list);
printk("student num: %d \t name: %s\n",node_p->num,node_p->name);
}
return 0;
fail_malloc:
kfree(node_p);
}
static void __exit listtest_exit(void)
{
return ;
}
module_init(listtest_init);
module_exit(listtest_exit);
MODULE_LICENSE("GPL");
struct list_head 内核链表范例 增删改查
最新推荐文章于 2022-06-12 18:20:05 发布
本文详细介绍了Linux内核中如何使用链表数据结构进行初始化、遍历、查找和删除节点的操作,并通过实例展示了这些操作的具体实现过程。
1474

被折叠的 条评论
为什么被折叠?



