分类: LINUX
2007-04-10 13:04:15
在我们日常程序中,常碰到写链表的情况。对于c++程序,stl提供了list和vector两个模板,使用起来很方便。如果限制编译器只能使用c,很多同学都自己封装相关接口,花费了不必要的时间。linux内核提供了基于面向对象思想的链表:include/linux/list.h。
转载请保留原创(msn and email:jinglexy at yahoo dot com dot cn),苏州科达科技上研所。
这里是从montavist
首先修改源程序,在#ifdef __KERNEL__及3个include语句的后面加入下面程序:
(蓝色是加入部分)
#include #include #elif 1 #define prefetch(x) 1 #define smp_wmb(x) 1 #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) );}) |
下面做一个测试程序:
#include #include #include #include "list.h" #define DEBUG do { \ printf("**************************\n"); \ printf("list 1:\n"); \ list_for_each(i, &list1) { \ mylist_t *ops = \ list_entry(i, \ mylist_t, list); \ printf("pf is %d\n", ops->pf); \ } \ \ printf("list 2:\n"); \ list_for_each(i, &list2) { \ mylist_t *ops = \ list_entry(i, \ mylist_t, list); \ printf("pf is %d\n", ops->pf); \ } \ } while(0); #if 1 typedef struct __mylist { int pf; char name[FILENAME_MAX]; struct list_head list; } mylist_t; #else typedef struct __mylist { struct list_head list; int pf; char name[FILENAME_MAX]; } mylist_t; #endif static LIST_HEAD(list1); /* define 2 list */ static LIST_HEAD(list2); int main(int argc, char *argv[]) { struct list_head *i; mylist_t elem1; mylist_t elem2; INIT_LIST_HEAD(&list1); INIT_LIST_HEAD(&list2); elem1.pf = 2008; elem2.pf = 8002; list_add(&elem1.list, &list1); list_del(&elem1.list); list_add(&elem1.list, &list1); list_add_tail(&elem2.list, &list1); DEBUG; /* move element to another list */ list_move_tail(&elem2.list, &list2); list_splice_init(&list1, &list2); /* merge */ DEBUG; return 0; } |
使用gcc编译,gcc test.c,运行程序,结果正是我们想要的。