struct list_head 内核链表范例 增删改查

#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");

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

developer_wgl

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值