这篇文章其实是根据xboot文件系统或者整个kernel都用到list_head而写的一个简单的示例,通过示例可以明白list_head的用法。
编写list_head.h文件,内容如下:
#ifndef _LIST_HEAD_
#define _LIST_HEAD_
struct list_head
{
struct list_head *prev,*next;
};
#endif
编写list_head.c文件,内容如下:
#include "list_head.h"
void list_head_init(struct list_head *entry)
{
entry->next = entry;
entry->prev = entry;
}
void _list_add(struct list_head *new,struct list_head *prev, struct list_head *next)
{
new->next = next;
next->prev= new;
new->prev= prev;
prev->next=new;
}
void list_add(struct list_head *new,struct list_head *old)
{
_list_add(new,old,old->next);
}
void list_add_tail(struct list_head *new,struct list_head *old)
{
_list_add(new,old->prev,old);
}
void list_del(struct list_head *entry,struct list_head *old)
{
entry->prev->next = entry->next;
entry->next->prev = entry->prev;
}
接着是main.c文件,内容如下:
#include <stdio.h>
#include <string.h>
#include "list_head.h"
struct student{
struct list_head stu_list;
int age;
char name[10];
};
struct list_head g_stu_entry;
int main(int argc, char const *argv[])
{
struct student st1;
struct student st2;
struct student st3;
struct student *st;
struct list_head *pos;
list_head_init(&g_stu_entry);
st1.age = 10;
memcpy(st1.name,"zhangsan",sizeof("zhangsan"));
list_add_tail(&st1.stu_list,&g_stu_entry);
st2.age = 20;
memcpy(st2.name,"lisi",sizeof("lisi"));
list_add_tail(&st2.stu_list,&g_stu_entry);
st3.age = 30;
memcpy(st3.name,"wangwu",sizeof("wangwu"));
list_add_tail(&st3.stu_list,&g_stu_entry);
printf("st1=0x%0x\r\n",&st1);
for(pos=g_stu_entry.next;pos!=&g_stu_entry;pos=pos->next){
st=(struct student *)((char *)pos-(char *)(&((struct student *)0)->stu_list));
printf("st=0x%0x\r\n",st);
printf("*st.age=%d\r\n",st->age);
printf("*st.name=%s\r\n",st->name);
}
printf("del some point...\r\n");
list_del(&st2.stu_list,&g_stu_entry);
for(pos=g_stu_entry.next;pos!=&g_stu_entry;pos=pos->next){
st=(struct student *)((char *)pos-(char *)(&((struct student *)0)->stu_list));
printf("st=0x%0x\r\n",st);
printf("*st.age=%d\r\n",st->age);
printf("*st.name=%s\r\n",st->name);
}
return 0;
}
最后,执行文件:
$ gcc *.c -o list_head
$ ./list_head
st1=0xf7b986f0
st=0xf7b986f0
*st.age=10
*st.name=zhangsan
st=0xf7b98710
*st.age=20
*st.name=lisi
st=0xf7b98730
*st.age=30
*st.name=wangwu
del some point...
st=0xf7b986f0
*st.age=10
*st.name=zhangsan
st=0xf7b98730
*st.age=30
*st.name=wangwu
具体分析,就不多说了。
网友评论