klist.h
#ifndefの_KLIST_H_
#define _KLIST_H_
構造体LIST_HEAD {
構造体LIST_HEAD *次回、* PREV。
}。
#define LIST_HEAD_INIT(名){&(名)、&(名)}
#define LIST_HEAD(名)\
構造体LIST_HEAD名= LIST_HEAD_INIT(名)
#define container_of(PTR、タイプ、メンバー)({\
CONST typeof演算(((タイプ*)0) - >メンバー)* __ mptr =(PTR)。\
(タイプ*)((CHAR *)__ mptr - ((size_tの)&((タイプ*)0) - >メンバー));})
#define LIST_ENTRY(PTR、タイプ、メンバー)\
container_of(PTR、タイプ、メンバー)
#define list_first_entry(PTR、タイプ、メンバー)\
LIST_ENTRY((PTR) - >次に、型部材)
#define list_next_entry(POS、メンバー)\
LIST_ENTRY((POS) - > member.next、typeof演算(*(POS))、メンバー)
#define list_for_each_entry(POS、頭、体)\
(POS = list_first_entry(頭部、typeof演算(* POS)、メンバー)のために、\
!&POS->メンバー=(ヘッド); \
POS = list_next_entry(POS、メンバー))
空list_add(構造体LIST_HEAD *新しい、構造体LIST_HEAD *ヘッド)。
#endifの
klist.c
書式#include <stdbool.h>
#include "klist.h"
静的インライン無効INIT_LIST_HEAD(構造体LIST_HEAD *リスト)
{
リスト - >次=リスト。
リスト - > PREV =リスト。
}
BOOL __list_add_valid(構造体LIST_HEAD *新しい、構造体LIST_HEAD * PREV、
構造体LIST_HEAD *次)
{
()(ネクスト> PREV!= PREV)||(prev->次の!=次)||(新==前|| ==新しい次)の場合
falseを返します。
trueを返します。
}
静的インライン無効__list_add(構造体LIST_HEAD *新しいです、
構造体LIST_HEAD * PREV、
構造体LIST_HEAD *次)
{
もし(!__ list_add_valid(新しい、PREV、NEXT))
リターン;
ネクスト> PREV =新しいです。
新規作成 - >次=次回。
新規作成 - > PREV =前;
prev->next = new;
}
void list_add(struct list_head *new, struct list_head *head)
{
__list_add(new, head, head->next);
}
test.c
#include <stdio.h>
#include "klist.h"
struct my_task_list {
int val ;
struct list_head mylist;
};
int main(int argc, char const *argv[])
{
LIST_HEAD(header_task);
struct my_task_list my_first_task = {
.val = 1,
.mylist = LIST_HEAD_INIT(my_first_task.mylist)
};
struct my_task_list my_second_task = {
.val = 2,
.mylist = LIST_HEAD_INIT(my_second_task.mylist)
};
list_add(&my_first_task.mylist, &header_task);
list_add(&my_second_task.mylist, &header_task);
struct my_task_list *pos;
list_for_each_entry(pos, &header_task, mylist) {
printf("%d\n", pos->val);
}
return 0;
}