打印

反思基础-研究kernel层次的架构

[复制链接]
177|0
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
没名字的人|  楼主 | 2018-10-3 16:28 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
由于最近一直在研究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 "list.h"

#define DEBUG

#ifdef DEBUG

#define dprintf(fmt, arg...)  printf("####list debug###"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("len is offset at std = %d\n", offset(struct std, len));

    struct    list_head list;

    INIT_LIST_HEAD(&list);

    dprintf("list head = 0x%x, list->next = 0x%x, list->prev = 0x%x\n", list, list.next, list.prev);

    struct man man_head = {

        .name = "sjf",

        .heigh = 172,

    };

    struct man man_new = {

        .name = "zwj",

        .heigh = 165,

    };

    struct man* tp_man = container_of(&man_head.man_list, struct man, man_list);

    dprintf("man_head name:%s\n", 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("man_head heigh = %d\n", tp_man->heigh);

    dprintf("man_head.name = %s, man_new.name = %s\n", (container_of(list.next, struct man, man_list))->name, (container_of(list.next->next, struct man, man_list))->name);

    return 0;

}

使用特权

评论回复

相关帖子

发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

420

主题

432

帖子

0

粉丝