由于最近一直在研究kernel层次的架构,比如cgroup,arch的建立,irq的建立,linux timer机制,sysfs这些。里面看到了很多list结构,想着自己在学校可是深入研究list和kfifo的,于是就自己重新写offset,contrainer_of宏,list。结果写的很纠结啊,调试了一段时间才整出来,这说明什么?基础不牢固啊··············
看来得重新学习下算法部分啊。
附加部分debug程序:
/*************** list.h *********************/
#ifndef _LIST_H_
#define _LIST_H_
#define offset(type, member) ((size_t)&(((type*) 0)->member))
#if 1
#define container_of(addr, type, member) \
(type*)((char*)(addr) - offset(type, member))
#endif
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;
}
static inline void list_add(struct list_head* new, struct list_head* head)
{
head->next->prev = new;
new->prev = head;
new->next = head->next;
head->next = new;
}
#endif
/***************main.c *********************/
#include <stdio.h>
#include &quot;list.h&quot;
#define DEBUG
#ifdef DEBUG
#define dprintf(fmt, arg...) printf(&quot;####list debug###&quot;fmt, ##arg)
#else
#define dprintf(fmt, arg...)
#endif
struct std{
const char* name;
int len;
struct list_head std_list;
};
struct man{
const char* name;
int heigh;
struct list_head man_list;
};
int main()
{
struct std std;
dprintf(&quot;len is offset at std = %d\n&quot;, offset(struct std, len));
struct list_head list;
INIT_LIST_HEAD(&list);
dprintf(&quot;list head = 0x%x, list->next = 0x%x, list->prev = 0x%x\n&quot;, list, list.next, list.prev);
struct man man_head = {
.name = &quot;sjf&quot;,
.heigh = 172,
};
struct man man_new = {
.name = &quot;zwj&quot;,
.heigh = 165,
};
struct man* tp_man = container_of(&man_head.man_list, struct man, man_list);
dprintf(&quot;man_head name:%s\n&quot;, tp_man->name);
list_add(&man_head.man_list, &list);
list_add(&man_new.man_list, &man_head.man_list);
tp_man = container_of(list.next, struct man, man_list);
dprintf(&quot;man_head heigh = %d\n&quot;, tp_man->heigh);
dprintf(&quot;man_head.name = %s, man_new.name = %s\n&quot;, (container_of(list.next, struct man, man_list))->name, (container_of(list.next->next, struct man, man_list))->name);
return 0;
} |