拒绝造轮子!如何移植并使用Linux内核的通用链表(附完整代码实现)

拒绝造轮子!如何移植并使用Linux内核的通用链表(附完整代码实现),第1张

概述在实际的工作中,我们可能会经常使用链表结构来存储数据,特别是嵌入式开发,经常会使用linux内核最经典的双向链表 list_head。本篇文章详细介绍了Linux内核的通用链表是如何实现的,对于经常使

在实际的工作中,我们可能会经常使用链表结构来存储数据,特别是嵌入式开发,经常会使用linux内核最经典的双向链表 List_head。本篇文章详细介绍了linux内核的通用链表是如何实现的,对于经常使用的函数都给出了详细的说明和测试用例,并且移植了linux内核的链表结构,在任意平台都可以方便的调用内核已经写好的函数。建议收藏,以备不时之需!

@

目录链表简介单链表双链表循环链表Linux内核中的链表链表的定义链表的初始化内核实现说明举例链表增加节点内核实现说明举例链表删除节点内核实现说明举例链表替换节点内核实现说明举例链表删除并插入节点内核实现说明举例链表的合并内核实现说明用例链表的遍历内核实现说明举例疑惑解答list.h移植源码

链表简介

  链表是一种常用的组织有序数据的数据结构,它通过指针将一系列数据节点连接成一条数据链,是线性表的一种重要实现方式。相对于数组,链表具有更好的动态性,建立链表时无需预先知道数据总量,可以随机分配空间,可以高效地在链表中的任意位置实时插入或删除数据。
  通常链表数据结构至少应包含两个域:数据域和指针域,数据域用于存储数据,指针域用于建立与下一个节点的联系。按照指针域的组织以及各个节点之间的联系形式,链表又可以分为单链表、双链表、循环链表等多种类型,下面分别给出这几类常见链表类型的示意图:

单链表

  单链表是最简单的一类链表,它的特点是仅有一个指针域指向后继节点(next),因此,对单链表的遍历只能从头至尾(通常是NulL空指针)顺序进行。

双链表

  通过设计前驱和后继两个指针域,双链表可以从两个方向遍历,这是它区别于单链表的地方。如果打乱前驱、后继的依赖关系,就可以构成"二叉树";如果再让首节点的前驱指向链表尾节点、尾节点的后继指向首节点,就构成了循环链表;如果设计更多的指针域,就可以构成各种复杂的树状数据结构。

循环链表

  循环链表的特点是尾节点的后继指向首节点。前面已经给出了双链表的示意图,它的特点是从任意一个节点出发,沿两个方向的任何一个,都能找到链表中的任意一个数据。如果去掉前驱指针,就是单循环链表。

  关于链表的更详细的内容可以看这两篇博客
史上最全单链表的增删改查反转等 *** 作汇总以及5种排序算法
详解双向链表的基本 *** 作.

linux内核中的链表

  上面介绍了普通链表的实现方式,可以看到数据域都是包裹在节点指针中的,通过节点指针访问下一组数据。但是 linux内核的链表实现可以说比较特殊,只有前驱和后继指针,而没有数据域。链表的头文件是在include/List.h(linux2.6内核)下。在实际工作中,也可以将内核中的链表拷贝出来供我们使用,就需不要造轮子了。

链表的定义

  内核链表只有前驱和后继指针,并不包含数据域,这个链表具备通用性,使用非常方便。因此可以很容易的将内核链表结构体包含在任意数据的结构体中,非常容易扩展。我们只需要将链表结构体包括在数据结构体中就可以。下面看具体的代码。


  内核链表的结构

//链表结构struct List_head{    struct List_head *prev;    struct List_head *next;};

  当需要用内核的链表结构时,只需要在数据结构体中定义一个struct List_head{}类型的结构体成员对象就可以。这样,我们就可以很方便地使用内核提供给我们的一组标准接口来对链表进行各种 *** 作。我们定义一个学生结构体,里面包含学号和数学成绩。结构体如下:

 struct student{    struct List_head List;//暂且将链表放在结构体的第一位    int ID;    int math;   };
链表的初始化内核实现
#define List_head_INIT(name) { &(name),&(name) }#define List_head(name) \	struct List_head name = List_head_INIT(name)    static inline voID INIT_List_head(struct List_head *List){	List->next = List;	List->prev = List;}
说明

  INIT_List_headList_head都可以初始化链表,二者的区别如下:
  List_head(stu_List) 初始化链表时会顺便创建链表对象。

//List_head(stu_List)展开如下struct List_head stu_List= { &(stu_List),&(stu_List) };

  INIT_List_head(&stu1.stu_List) 初始化链表时需要我们已经有了一个链表对象stu1_List

  `我们可以看到链表的初始化其实非常简单,就是让链表的前驱和后继都指向了自己。

举例
INIT_List_head(&stu1.stu_List);
链表增加节点内核实现
/* * Insert a new entry between two kNown consecutive entrIEs. * * This is only for internal List manipulation where we kNow * the prev/next entrIEs already! */#ifndef CONfig_DEBUG_Liststatic inline voID __List_add(struct List_head *new,struct List_head *prev,struct List_head *next){	next->prev = new;	new->next = next;	new->prev = prev;	prev->next = new;}#elseextern voID __List_add(struct List_head *new,struct List_head *next);#endif/** * List_add - add a new entry * @new: new entry to be added * @head: List head to add it after * * Insert a new entry after the specifIEd head. * This is good for implementing stacks. */#ifndef CONfig_DEBUG_Liststatic inline voID List_add(struct List_head *new,struct List_head *head){	__List_add(new,head,head->next);}#elseextern voID List_add(struct List_head *new,struct List_head *head);#endif/** * List_add_tail - add a new entry * @new: new entry to be added * @head: List head to add it before * * Insert a new entry before the specifIEd head. * This is useful for implementing queues. */static inline voID List_add_tail(struct List_head *new,head->prev,head);}
说明

  List_add为头插法,即在链表头部(head节点)前插入节点。最后打印的时候,先插入的先打印,后插入的后打印。例如原链表为1->2->3,使用List_add插入4后变为,4->1->2->3。因为链表时循环的,而且通常没有首尾节点的概念,所以可以把任何一个节点当成head。
  同理,List_add_tail为尾插法,即在链表尾部(head节点)插入节点。最后打印的时候,先插入的后打印,后插入的先打印。例如原链表为1->2->3,使用List_add_tail插入4后变为,1->2->3->4。

举例
#include "myList.h"#include <stdio.h>#include <stdlib.h>struct student{    struct List_head stu_List;    int ID;    int math;   };int main(){    struct student *p;    struct student *q;    struct student stu1;    struct student stu2;      struct List_head *pos;    //链表的初始化    INIT_List_head(&stu1.stu_List);    INIT_List_head(&stu2.stu_List);    //头插法创建stu stu1链表     for (int i = 0;i < 6;i++) {         p = (struct student *)malloc(sizeof(struct student));         p->ID=i;         p->math = i+80;         //头插法         List_add(&p->stu_List,&stu1.stu_List);         //尾插法         //List_add_tail(&p->List,&stu.List);     }         printf("List_add: \r\n");    List_for_each(pos,&stu1.stu_List) {        printf("ID = %d,math = %d\n",((struct student*)pos)->ID,((struct student*)pos)->math);    }        //尾插法创建stu stu1链表     for (int i = 0;i < 6;i++) {         p = (struct student *)malloc(sizeof(struct student));         p->ID=i;         p->math = i+80;         //头插法         //List_add(&p->stu_List,&stu1.stu_List);         //尾插法         List_add_tail(&p->stu_List,&stu2.stu_List);     }         printf("List_add_tail: \r\n");    List_for_each(pos,&stu2.stu_List) {        printf("ID = %d,((struct student*)pos)->math);    }    return 0; }

链表删除节点内核实现
//原来内核设置的删除链表后的指向位置// # define POISON_POINTER_DELTA 0// #define List_POISON1  ((voID *) 0x00100100 + POISON_POINTER_DELTA)// #define List_POISON2  ((voID *) 0x00200200 + POISON_POINTER_DELTA)//这里我们设置为NulL 内核中定义NulL 为0#define NulL ((voID *)0)#define List_POISON1  NulL#define List_POISON2  NulL/* * Delete a List entry by making the prev/next entrIEs * point to each other. * * This is only for internal List manipulation where we kNow * the prev/next entrIEs already! */static inline voID __List_del(struct List_head * prev,struct List_head * next){	next->prev = prev;	prev->next = next;}/** * List_del - deletes entry from List. * @entry: the element to delete from the List. * Note: List_empty() on entry does not return true after this,the entry is * in an undefined state. */#ifndef CONfig_DEBUG_Liststatic inline voID List_del(struct List_head *entry){	__List_del(entry->prev,entry->next);	entry->next = List_POISON1;	entry->prev = List_POISON2;}#elseextern voID List_del(struct List_head *entry);#endif
说明

  链表删除之后,entry的前驱和后继会分别指向List_POISON1List_POISON2,这个是内核设置的一个区域,但是在本例中将其置为了NulL

举例
#include "myList.h"#include <stdio.h>#include <stdlib.h>struct student{    struct List_head stu_List;    int ID;    int math;   };int main(){    struct student *p;    struct student *q;    struct student stu1;    struct student stu2;      struct List_head *pos1;    //注意这里的pos2,后面会解释为什么定义为    struct student *pos2;    //stu = (struct student*)malloc(sizeof(struct student));    //链表的初始化    INIT_List_head(&stu1.stu_List);    INIT_List_head(&stu2.stu_List);    List_head(stu);    //头插法创建stu stu1链表     for (int i = 0;i < 6;i++) {         p = (struct student *)malloc(sizeof(struct student));         p->ID=i;         p->math = i+80;         //头插法         List_add(&p->stu_List,&stu.List);     }         printf("List_add: \r\n");    List_for_each(pos1,((struct student*)pos1)->ID,((struct student*)pos1)->math);    }        //删除    List_for_each_entry(pos2,&stu1.stu_List,stu_List) {        if (pos2->ID == 4) {            List_del(&pos2->stu_List);            break;        }    }        printf("List_del\r\n");    List_for_each_entry(pos2,stu_List) {        printf("ID = %d,pos2->ID,pos2->math);    }    return 0; }

链表替换节点内核实现
/** * List_replace - replace old entry by new one * @old : the element to be replaced * @new : the new element to insert * * If @old was empty,it will be overwritten. */static inline voID List_replace(struct List_head *old,struct List_head *new){	new->next = old->next;	new->next->prev = new;	new->prev = old->prev;	new->prev->next = new;}static inline voID List_replace_init(struct List_head *old,struct List_head *new){	List_replace(old,new);	INIT_List_head(old);//重新初始化}
@H_301_273@说明

  List_replace使用新的节点替换旧的节点。
  List_replace_initList_replace不同之处在于,List_replace_init会将旧的节点重新初始化,让前驱和后继指向自己。

举例
#include "myList.h"#include <stdio.h>#include <stdlib.h>struct student{    struct List_head stu_List;    int ID;    int math;   };int main(){    struct student *p;    struct student *q;    struct student stu1;    struct student stu2;      struct List_head *pos1;    struct student *pos2;    struct student new_obj={.ID=100,.math=100};     //stu = (struct student*)malloc(sizeof(struct student));    //链表的初始化    INIT_List_head(&stu1.stu_List);    INIT_List_head(&stu2.stu_List);    List_head(stu);    //头插法创建stu stu1链表     for (int i = 0;i < 6;i++) {         p = (struct student *)malloc(sizeof(struct student));         p->ID=i;         p->math = i+80;         //头插法         List_add(&p->stu_List,&stu.List);     }    printf("List_add: \r\n");    List_for_each(pos1,((struct student*)pos1)->math);    }     //替换    List_for_each_entry(pos2,stu_List) {        if (pos2->ID == 4) {            List_replace(&pos2->stu_List,&new_obj.stu_List);            break;        }    }    printf("List_replace\r\n");    List_for_each_entry(pos2,pos2->math);    }    return 0; }

链表删除并插入节点内核实现
/** * List_move - delete from one List and add as another's head * @List: the entry to move * @head: the head that will precede our entry */static inline voID List_move(struct List_head *List,struct List_head *head){	__List_del(List->prev,List->next);	List_add(List,head);}/** * List_move_tail - delete from one List and add as another's tail * @List: the entry to move * @head: the head that will follow our entry */static inline voID List_move_tail(struct List_head *List,List->next);	List_add_tail(List,head);}
说明

  List_move函数实现的功能是删除List指向的节点,同时将其以头插法插入到head中。List_move_tailList_move功能类似,只不过是将List节点插入到了head的尾部。

举例
#include "myList.h"#include <stdio.h>#include <stdlib.h>struct student{    struct List_head stu_List;    int ID;    int math;   };int main(){    struct student *p;    struct student *q;    struct student stu1;    struct student stu2;      struct List_head *pos1;    struct student *pos2;    struct student new_obj={.ID=100,((struct student*)pos1)->math);    }     //移位替换    List_for_each_entry(pos2,stu_List) {        if (pos2->ID == 0) {            List_move(&pos2->stu_List,&stu1.stu_List);            break;        }    }    printf("List_move\r\n");    List_for_each_entry(pos2,pos2->math);    }    return 0; }

链表的合并内核实现
static inline voID __List_splice(struct List_head *List,struct List_head *head){	struct List_head *first = List->next;	struct List_head *last = List->prev;	struct List_head *at = head->next;	first->prev = head;	head->next = first;	last->next = at;	at->prev = last;}/** * List_splice - join two Lists * @List: the new List to add. * @head: the place to add it in the first List. */static inline voID List_splice(struct List_head *List,struct List_head *head){	if (!List_empty(List))		__List_splice(List,head);}/** * List_splice_init - join two Lists and reinitialise the emptIEd List. * @List: the new List to add. * @head: the place to add it in the first List. * * The List at @List is reinitialised */static inline voID List_splice_init(struct List_head *List,struct List_head *head){	if (!List_empty(List)) {		__List_splice(List,head);		INIT_List_head(List);//置空	}}
说明

  List_splice完成的功能是合并两个链表。假设当前有两个链表,表头分别是stu_List1stu_List2(都是struct List_head变量),当调用List_splice(&stu_List1,&stu_List2)时,只要stu_List1非空,stu_List1链表的内容将被挂接在stu_List2链表上,位于stu_List2stu_List2.next(原stu_List2表的第一个节点)之间。新stu_List2链表将以原stu_List1表的第一个节点为首节点,而尾节点不变。

  List_splice_initList_splice类似,只不过在合并完之后,调用INIT_List_head(List)将List设置为空链。

用例
#include "myList.h"#include <stdio.h>#include <stdlib.h>struct student{    struct List_head stu_List;    int ID;    int math;   };int main(){    struct student *p;    struct student *q;    struct student stu1;    struct student stu2;      struct List_head *pos1;    struct student *pos2;    struct student new_obj={.ID=100,.math=100};     //stu = (struct student*)malloc(sizeof(struct student));    //链表的初始化    INIT_List_head(&stu1.stu_List);    INIT_List_head(&stu2.stu_List);    List_head(stu);    //头插法创建stu1 List链表     for (int i = 0;i < 6;i++) {         p = (struct student *)malloc(sizeof(struct student));         p->ID=i;         p->math = i+80;         //头插法         List_add(&p->stu_List,&stu.List);     }    printf("stu1: \r\n");    List_for_each(pos1,((struct student*)pos1)->math);    }    //头插法创建stu2 List 链表     for (int i = 0;i < 3;i++) {         q = (struct student *)malloc(sizeof(struct student));         q->ID=i;         q->math = i+80;         //头插法         List_add(&q->stu_List,&stu2.stu_List);         //尾插法         //List_add_tail(&p->List,&stu.List);     }    printf("stu2: \r\n");    List_for_each(pos1,((struct student*)pos1)->math);    }    //合并    List_splice(&stu1.stu_List,&stu2.stu_List);    printf("List_splice\r\n");    List_for_each(pos1,&stu2.stu_List) {        printf("stu2 ID = %d,((struct student*)pos1)->math);    }        return 0; }

链表的遍历内核实现
//计算member在type中的位置#define offsetof(type,member)  (size_t)(&((type*)0)->member)//根据member的地址获取type的起始地址#define container_of(ptr,type,member) ({          \        const typeof(((type *)0)->member)*__mptr = (ptr);    \    (type *)((char *)__mptr - offsetof(type,member)); })    /** * List_entry - get the struct for this entry * @ptr:	the &struct List_head pointer. * @type:	the type of the struct this is embedded in. * @member:	the name of the List_struct within the struct. */#define List_entry(ptr,member) \	container_of(ptr,member)/** * List_first_entry - get the first element from a List * @ptr:	the List head to take the element from. * @type:	the type of the struct this is embedded in. * @member:	the name of the List_struct within the struct. * * Note,that List is expected to be not empty. */#define List_first_entry(ptr,member) \	List_entry((ptr)->next,member)/** * List_for_each	-	iterate over a List * @pos:	the &struct List_head to use as a loop cursor. * @head:	the head for your List. */#define List_for_each(pos,head) \	for (pos = (head)->next; prefetch(pos->next),pos != (head); \        	pos = pos->next)/** * __List_for_each	-	iterate over a List * @pos:	the &struct List_head to use as a loop cursor. * @head:	the head for your List. * * This variant differs from List_for_each() in that it's the * simplest possible List iteration code,no prefetching is done. * Use this for code that kNows the List to be very short (empty * or 1 entry) most of the time. */#define __List_for_each(pos,head) \	for (pos = (head)->next; pos != (head); pos = pos->next)/** * List_for_each_prev	-	iterate over a List backwards * @pos:	the &struct List_head to use as a loop cursor. * @head:	the head for your List. */#define List_for_each_prev(pos,head) \	for (pos = (head)->prev; prefetch(pos->prev),pos != (head); \        	pos = pos->prev)/** * List_for_each_safe - iterate over a List safe against removal of List entry * @pos:	the &struct List_head to use as a loop cursor. * @n:		another &struct List_head to use as temporary storage * @head:	the head for your List. */#define List_for_each_safe(pos,n,head) \	for (pos = (head)->next,n = pos->next; pos != (head); \		pos = n,n = pos->next)/** * List_for_each_entry	-	iterate over List of given type * @pos:	the type * to use as a loop cursor. * @head:	the head for your List. * @member:	the name of the List_struct within the struct. */#define List_for_each_entry(pos,member)				\	for (pos = List_entry((head)->next,typeof(*pos),member);	\	     prefetch(pos->member.next),&pos->member != (head); 	\	     pos = List_entry(pos->member.next,member))/** * List_for_each_entry_reverse - iterate backwards over List of given type. * @pos:	the type * to use as a loop cursor. * @head:	the head for your List. * @member:	the name of the List_struct within the struct. */#define List_for_each_entry_reverse(pos,member)			\	for (pos = List_entry((head)->prev,member);	\	     prefetch(pos->member.prev),&pos->member != (head); 	\	     pos = List_entry(pos->member.prev,member))/** * List_prepare_entry - prepare a pos entry for use in List_for_each_entry_continue() * @pos:	the type * to use as a start point * @head:	the head of the List * @member:	the name of the List_struct within the struct. * * Prepares a pos entry for use as a start point in List_for_each_entry_continue(). */#define List_prepare_entry(pos,member) \	((pos) ? : List_entry(head,member))/** * List_for_each_entry_continue - continue iteration over List of given type * @pos:	the type * to use as a loop cursor. * @head:	the head for your List. * @member:	the name of the List_struct within the struct. * * Continue to iterate over List of given type,continuing after * the current position. */#define List_for_each_entry_continue(pos,member) 		\	for (pos = List_entry(pos->member.next,&pos->member != (head);	\	     pos = List_entry(pos->member.next,member))/** * List_for_each_entry_from - iterate over List of given type from the current point * @pos:	the type * to use as a loop cursor. * @head:	the head for your List. * @member:	the name of the List_struct within the struct. * * Iterate over List of given type,continuing from current position. */#define List_for_each_entry_from(pos,member) 			\	for (; prefetch(pos->member.next),member))/** * List_for_each_entry_safe - iterate over List of given type safe against removal of List entry * @pos:	the type * to use as a loop cursor. * @n:		another type * to use as temporary storage * @head:	the head for your List. * @member:	the name of the List_struct within the struct. */#define List_for_each_entry_safe(pos,member)			\	for (pos = List_entry((head)->next,member),\		n = List_entry(pos->member.next,member);	\	     &pos->member != (head); 					\	     pos = n,n = List_entry(n->member.next,typeof(*n),member))/** * List_for_each_entry_safe_continue * @pos:	the type * to use as a loop cursor. * @n:		another type * to use as temporary storage * @head:	the head for your List. * @member:	the name of the List_struct within the struct. * * Iterate over List of given type,continuing after current point,* safe against removal of List entry. */#define List_for_each_entry_safe_continue(pos,member);		\	     &pos->member != (head);						\	     pos = n,member))/** * List_for_each_entry_safe_from * @pos:	the type * to use as a loop cursor. * @n:		another type * to use as temporary storage * @head:	the head for your List. * @member:	the name of the List_struct within the struct. * * Iterate over List of given type from current point,safe against * removal of List entry. */#define List_for_each_entry_safe_from(pos,member) 			\	for (n = List_entry(pos->member.next,member))/** * List_for_each_entry_safe_reverse * @pos:	the type * to use as a loop cursor. * @n:		another type * to use as temporary storage * @head:	the head for your List. * @member:	the name of the List_struct within the struct. * * Iterate backwards over List of given type,safe against removal * of List entry. */#define List_for_each_entry_safe_reverse(pos,member)		\	for (pos = List_entry((head)->prev,\		n = List_entry(pos->member.prev,n = List_entry(n->member.prev,member))
说明

  List_entry(ptr,member)可以得到节点结构体的地址,得到地址后就可以对结构体中的元素进行 *** 作了。依靠List_entry(ptr,member)函数,内核链表的增删查改都不需要知道List_head结构体所嵌入式的对象,就可以完成各种 *** 作。(为什么这里使用container_of来定义List_entry(ptr,member)结构体呢,下面会详细解释)
  List_first_entry(ptr,member)得到的是结构体中第一个元素的地址
  List_for_each(pos,head)是用来正向遍历链表的,pos相当于一个临时的节点,用来不断指向下一个节点。
  List_for_each_prev(pos,head)List_for_each_entry_reverse(pos,member)是用来倒着遍历链表的
  List_for_each_safe(pos,head)List_for_each_entry_safe(pos,member),这两个函数是为了避免在遍历链表的过程中因pos节点被释放而造成的断链这个时候就要求我们另外提供一个与pos同类型的指针n,在for循环中暂存pos下一个节点的地址。(内核的设计者考虑的真是全面!)
  List_prepare_entry(pos,member)用于准备一个结构体的首地址,用在List_for_each_entry_contine()
  List_for_each_entry_continue(pos,member)从当前pos的下一个节点开始继续遍历剩余的链表,不包括pos.如果我们将pos、head、member传入List_for_each_entry,此宏将会从链表的头节点开始遍历。
  List_for_each_entry_continue_reverse(pos,member)从当前的pos的前一个节点开始继续反向遍历剩余的链表,不包括pos。
  List_for_each_entry_from(pos,member)从pos开始遍历剩余的链表。
  List_for_each_entry_safe_continue(pos,member)从pos节点的下一个节点开始遍历剩余的链表,并防止因删除链表节点而导致的遍历出错。
  List_for_each_entry_safe_from(pos,member) 从pos节点开始继续遍历剩余的链表,并防止因删除链表节点而导致的遍历出错。其与List_for_each_entry_safe_continue(pos,member)的不同在于在第一次遍历时,pos没有指向它的下一个节点,而是从pos开始遍历。
  List_for_each_entry_safe_reverse(pos,member)从pos的前一个节点开始反向遍历一个链表,并防止因删除链表节点而导致的遍历出错。
  List_safe_reset_next(pos,member) 返回当前pos节点的下一个节点的type结构体首地址。

举例
#include "myList.h"#include <stdio.h>#include <stdlib.h>struct student{    struct List_head stu_List;    int ID;    int math;   };int main(){    struct student *p;    struct student *q;    struct student stu1;    struct student stu2;      struct List_head *pos1;    struct student *pos2;    struct student new_obj={.ID=100,((struct student*)pos1)->math);    }    printf("List_for_each_prev\r\n");    List_for_each_prev(pos1,&stu1.stu_List){        printf("stu2 ID = %d,((struct student*)pos1)->math);    }    return 0; }


  例子就不都写出来了,感兴趣的可以自己试试。

疑惑解答

  之前我们定义结构体的时候是把 struct List_head放在首位的,当使用List_for_each遍历的时候,pos获取的位置就是结构体的位置,也就是链表的位置。如下所示

 struct student{    struct List_head List;//暂且将链表放在结构体的第一位    int ID;    int math;   };
    List_for_each(pos,((struct student*)pos)->math);    }

  但是当我们把struct List_head List;放在最后时,pos获取的显然就已经不是链表的位置了,那么当我们再次调用List_for_each时就会出错。

 struct student{      int ID;    int math;       struct List_head List;//暂且将链表放在结构体的第一位};

  List_for_each_entry这个函数表示在遍历的时候获取entry,该宏中的pos类型为容器结构类型的指针,这与前面List_for_each中的使用的类型不再相同(这也就是为什么我们上面会分别定义pos1和pos2的原因了),不过这也是情理之中的事,毕竟现在的pos,我要使用该指针去访问数据域的成员age了;head是你使用INIT_List_head初始化的那个对象,即头指针,注意,不是头结点;member就是容器结构中的链表元素对象。使用该宏替代前面的方法。这个时候就要用到container_of这个宏了。(再一次感叹内核设计者的伟大)。

  关于container_of宏将在下一篇文章详细介绍,这里先知道如何使用就可以。

List.h移植源码

  这里需要注意一点,如果是在GNU中使用GCC进行程序开发,可以不做更改,直接使用上面的函数即可;但如果你想把其移植到windows环境中进行使用,可以直接将prefetch语句删除即可,因为prefetch函数它通过对数据手工预取的方法,减少了读取延迟,从而提高了性能,也就是prefetch是GCC用来提高效率的函数,如果要移植到非GNU环境,可以换成相应环境的预取函数或者直接删除也可,它并不影响链表的功能。

/* * @Description: 移植linux2.6内核List.h * @Version: V1.0 * @@R_419_6843@r: https://blog.csdn.net/qq_16933601 * @Date: 2020-09-12 22:54:51 * @LastEditors: Carlos * @LastEditTime: 2020-09-16 00:35:17 */#ifndef _MYList_H#define _MYList_H //原来链表删除后指向的位置,这里我们修改成 0// # define POISON_POINTER_DELTA 0// #define List_POISON1  ((voID *) 0x00100100 + POISON_POINTER_DELTA)// #define List_POISON2  ((voID *) 0x00200200 + POISON_POINTER_DELTA)#define NulL ((voID *)0)#define List_POISON1  NulL#define List_POISON2  NulL//计算member在type中的位置#define offsetof(type,member)  (size_t)(&((type*)0)->member)//根据member的地址获取type的起始地址#define container_of(ptr,member)); })//链表结构struct List_head{    struct List_head *prev;    struct List_head *next;};#define List_head_INIT(name) { &(name),&(name) }#define List_head(name) \	struct List_head name = List_head_INIT(name)    static inline voID INIT_List_head(struct List_head *List){	List->next = List;	List->prev = List;}static inline voID init_List_head(struct List_head *List){    List->prev = List;    List->next = List;}#ifndef CONfig_DEBUG_Liststatic inline voID __List_add(struct List_head *new,struct List_head *next);#endif//从头部添加/** * List_add - add a new entry * @new: new entry to be added * @head: List head to add it after * * Insert a new entry after the specifIEd head. * This is good for implementing stacks. */#ifndef CONfig_DEBUG_Liststatic inline voID List_add(struct List_head *new,struct List_head *head);#endif//从尾部添加static inline voID List_add_tail(struct List_head *new,struct List_head *head){    __List_add(new,head);}static inline  voID __List_del(struct List_head *prev,struct List_head *next){    prev->next = next;    next->prev = prev;}static inline voID List_del(struct List_head *entry){    __List_del(entry->prev,entry->next);    entry->next = List_POISON1;    entry->prev = List_POISON2;}static inline voID __List_splice(struct List_head *List,struct List_head *head){	struct List_head *first = List->next;	struct List_head *last = List->prev;	struct List_head *at = head->next;	first->prev = head;	head->next = first;	last->next = at;	at->prev = last;}/** * List_empty - tests whether a List is empty * @head: the List to test. */static inline int List_empty(const struct List_head *head){	return head->next == head;}/** * List_splice - join two Lists * @List: the new List to add. * @head: the place to add it in the first List. */static inline voID List_splice(struct List_head *List,head);}/** * List_replace - replace old entry by new one * @old : the element to be replaced * @new : the new element to insert * * If @old was empty,new);	INIT_List_head(old);}/** * List_move - delete from one List and add as another's head * @List: the entry to move * @head: the head that will precede our entry */static inline voID List_move(struct List_head *List,head);}#define List_entry(ptr,member) \    container_of(ptr,member)#define List_first_entry(ptr,member) \    List_entry((ptr)->next,member)#define List_for_each(pos,head) \    for (pos = (head)->next; pos != (head); pos = pos->next)/** * List_for_each_entry	-	iterate over List of given type * @pos:	the type * to use as a loop cursor. * @head:	the head for your List. * @member:	the name of the List_struct within the struct. */#define List_for_each_entry(pos,member)      \	for (pos = List_entry((head)->next,member);	\	     &pos->member != (head); 	\	     pos = List_entry(pos->member.next,member))/** * List_for_each_prev	-	iterate over a List backwards * @pos:	the &struct List_head to use as a loop cursor. * @head:	the head for your List. */#define List_for_each_prev(pos,head) \	for (pos = (head)->prev;  pos != (head); \        	pos = pos->prev)

  养成习惯,先赞后看!如果觉得写的不错,欢迎关注,点赞,收藏,转发,谢谢!
  以上代码均为测试后的代码。如有错误和不妥的地方,欢迎指出。

欢迎欢迎关注我的公众号:嵌入式与linux那些事,领取秋招笔试面试大礼包(华为小米等大厂面经,嵌入式知识点总结,笔试题目,简历模版等)和2000G学习资料。公众号主要分享linux驱动开发,数据结构与算法,计算机基础,C/C++等相关知识,有任何问题均可以加我微信,欢迎骚扰!。

总结

以上是内存溢出为你收集整理的拒绝造轮子!如何移植并使用Linux内核的通用链表(附完整代码实现)全部内容,希望文章能够帮你解决拒绝造轮子!如何移植并使用Linux内核的通用链表(附完整代码实现)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/yw/1014638.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存