1、内核链原理及作用
(1)内核链表默认实现时,有头结点
(2)虽然每个节点多占用一个指针(4个字节),但是可以忽略,双链表在做删除节点和插入节点等操作时,会快很多,比如不需要定义plast,pPrev,去保存可能被断开的节点地址,因为他有双向指针,里面有前前后后所以地址的保存。
(3)内核链表中自己实现了一个纯链表(纯链表就是没有数据区域,只有前后向指针)的封装,以及纯链表的各种操作函数(节点创建、插入、删除、遍历······)。这个纯链表本身自己没有任何用处,它的用法是给我们具体链表作为核心来调用。
(4)内核使用最终目的之一:我们可以通过遍历head来实现drive的遍历,遍历函数在list.h中已经实现,通过head链表,来操作驱动,实质上就是操作结构体的某个成员变量来操作整个结构体,每个驱动结构体里面都有一个head链表的节点,这些节点组成了整个head链表,从当前驱动结构体里面的链表节点,通过container_of宏,可以得到整个结构体的首地址,然后去操作其他成员的数据
struct driver
{
char name[20]; // 驱动名称
int id; // 驱动id编号
struct driver_info info; // 驱动信息
struct list_head head; // 内嵌的内核链表成员
};
struct list_head
{
struct list_head *next,*prev;
}
2、内核链实际代码应用
(1)list.h中有如下定义
struct list_head { //list_head可以用去定义一个这个结构体类型的变量
struct list_head *next, *prev;
};
#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 list_add(struct list_head *new, struct list_head *head)
{
__list_add(new, head, head->next);
}
(2)在链表尾部添加一个N个节点
struct list_head RTPbuf_head = LIST_HEAD_INIT(RTPbuf_head);
typedef struct _rtpbuf 这个结构体是我们真正需要分配内存的,按照我们的需要添加变量,比如驱动所有信息
{
struct list_head list;
HI_S32 len;
char * buf;
}RTPbuf_s;
for (i = 0; i < n; i++)
{
RTPbuf_s *p = (RTPbuf_s *)malloc(sizeof(RTPbuf_s)); 申请内存
//初始化申请到的结构体RTPbuf_s里面嵌入的链表list,让结构体链表list里面的两个指针都指向list
INIT_LIST_HEAD(&(p->list)); //p->list,就是上面结构体链表变量,函数接收struct list_head的指针,所以取地址
lens = pstStream->pstPack[i].u32Len-pstStream->pstPack[i].u32Offset;
p->buf = (char *)malloc(lens);
p->len = lens;
memcpy(p->buf,pstStream->pstPack[i].pu8Addr+pstStream->pstPack[i].u32Offset,lens);
//尾部添加一个新的节点p,RTPbuf_head是事先定义好的一个链表变量,取地址后传入,用来当链表的头
list_add_tail(&(p->list),&RTPbuf_head); //RTPbuf_head定义时就初始化了
count++;
//printf("count = %d\n",count);
}