(5)、遍历链表
/**
* list_for_each - iterate over a list
* @pos: the &struct list_head to use as a loop cursor.
* @head: the head for your list.
*/
#define list_for_each(pos, head) \
for (pos = (head)->next; prefetch(pos->next), pos != (head); \
pos = pos->next)
遍历链表也是一个宏定义,且是一个没加{}的for循环,
因此调用此函数时一定要加上{}。
使用时注意参数pos是指针类型,我们要定义一个list_head类型的
结构体变量指针传送给这个函数。
4、链表使用实例
-
- #include <linux/kernel.h>
- #include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/list.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("monkeyzx");
MODULE_DESCRIPTION("Mylist Module");
MODULE_VERSION("V1.0");
struct student
{
char name[100];
int id;
struct list_head list;
};
struct student *pstudent;
struct student *tmp_student;
struct list_head student_list;
struct list_head *pos;
int __init mylist_init()
{
int i = 0;
INIT_LIST_HEAD(&student_list);
pstudent = kmalloc(sizeof(struct student)*5, GFP_KERNEL);
memset(pstudent, 0, sizeof(struct student)*5);
for(i=0; i<5; i++)
{
sprintf(pstudent[i].name, "Student %d", i+1);
pstudent[i].id = i + 1;
list_add(&(pstudent[i].list), &student_list);
}
list_for_each(pos, &student_list)
{
tmp_student = list_entry(pos, struct student, list);
printk("<0>student %d name: %s\n", tmp_student->id, tmp_student->name);
}
}
void __exit mylist_exit()
{
int i = 0;
for(i=0; i<5; i++)
{
list_del(&(pstudent[i].list));
}
kfree(pstudent);
}
module_init(mylist_init);
module_exit(mylist_exit);
makefile文件如下
- ifneq ($(KERNELRELEASE),)
-
- obj-m := mylist.o
-
- else
-
- KDIR := /lib/modules/2.6.18-53.el5/build
- all:
- make -C $(KDIR) M=$(PWD) modules
- clean:
- rm -f *.ko *.o *.mod.o *.mod.c *.symvers
-
- endif
