你好,游客 登录 注册 搜索
背景:
阅读新闻

Linux内核链表基础

[日期:2012-08-29] 来源:Linux社区  作者:xiahouzuoxin [字体:大 中 小]

(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、链表使用实例

  1. #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文件如下

    1. ifneq ($(KERNELRELEASE),)  
    2.   
    3. obj-m := mylist.o  
    4.   
    5. else  
    6.       
    7. KDIR := /lib/modules/2.6.18-53.el5/build  
    8. all:  
    9.     make -C $(KDIR) M=$(PWD) modules  
    10. clean:  
    11.     rm -f *.ko *.o *.mod.o *.mod.c *.symvers  
    12.   
    13. endif
    linux
    相关资讯       Linux内核开发 
    本文评论   查看全部评论 (0)
    表情: 表情 姓名: 字数

           

    评论声明
    • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
    • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
    • 本站管理人员有权保留或删除其管辖留言中的任意内容
    • 本站有权在网站内转载或引用您的评论
    • 参与本评论即表明您已经阅读并接受上述条款