内核list.h在用户态使用举例

1. list的定义

struct 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;
}
2.引用方法

   在结构体重包含struct list_head,该结构体可位于任何字段,一个结构体中可以包含多个struct list_head.

 

struct mylist
{
   void *data;
   struct list_head use;
   struct list_head free;
};

3. 根据list变量获取结构体

 

#define list_entry(ptr, type, member) \
        container_of(ptr, type, member)
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#define container_of(ptr, type, member) ({\
           const typeof( ((type *)0)->member ) *__mptr = (ptr);\
           (type *)( (char *)__mptr - offsetof(type,member) );})


例如,struct list_item结构如下

struct list_item
{
    void *data;
    struct list_head list;
};

struct list_head *pos;
struct list_item *p = list_entry(pos, struct list_item, list);
p即为结构体指针。


4. 操作举例

struct list_item
{
   int id;
   struct list_head list;
};

int main()
{
  struct list_item *tmp;
  struct list_head *pos, *p;
  int i;
  
  //定义成员
  struct list_item mylist;
  //初始化链表
  INIT_LIST_HEAD(&mylist.list);

  for(int i = 0; i < 5; i++)
  {
       tmp = (list_item*)malloc(sizeof(struct list_item));
       tmp->id = i;
       list_add(&tmp->list, &mylist->list);
  }
  
   //遍历
  list_for_each(pos, &mylist.list)
  {
       tmp = list_entry(pos, struct list_item, list);
       printf("id = %d\n",tmp->id);
  }
}


你可能感兴趣的:(Linux)