Linux内核链表listnode

  在Init.cpp的code中,大量使用了listnode表示链表的一个节点。这样的好处显而易见,那就是减少了大量的代码量。假如现在要使用struct example构造一个链表,按以前的做法,可以写成:

样例

struct example_1
{
    struct example_1 *next;
    struct example_1 *previous;
    int a;
    char b;
}

  现在想构建一个新的struct example_2链表,按上面的做法,又要重写:

struct example_2
{
    struct example_2 *next;
    struct example_2 *previous;
    int c;
    char d;
    ...
}

  Linux提供了listnode结构体,它封装好了next,prev指针,将一个listnode结构体放到需要组成链表的结构体中,这个结构体便成为链表的一个节点。

/system/core/include/cutils/list.h

struct listnode
{
    struct listnode *next;
    struct listnode *prev;
};

  看看Init.h中struct action,struct command和struct trigger的关系。struct action中有多个listnode成员,决定了struct action以什么方式组成链表和包含的trigger,command链表。

/system/core/init/init.h

struct action {
        /* node in list of all actions */
    struct listnode alist;
        /* node in the queue of pending actions */
    struct listnode qlist;
        /* node in list of actions for a trigger */
    struct listnode tlist;

    unsigned hash;

        /* list of actions which triggers the commands*/
    struct listnode triggers;
    struct listnode commands;
    struct command *current;
};
struct command
{
        /* list of commands in an action */
    struct listnode clist;

    int (*func)(int nargs, char **args);

    int line;
    const char *filename;

    int nargs;
    char *args[1];
};
struct trigger {
    struct listnode nlist;
    const char *name;
};

  下图展示了这三个结构体的关系。将一个commond结构体的clist成员作为一个action结构体的commands成员,可以视为该action结构体携带了这个command。同理,将一个trigger结构体的rlist成员作为一个action结构体的triggers成员,可以视为该action结构体携带了这个trigger。将每个action结构体的alist成员作为action_list链表的一个节点,可以将所有的action添加到一个链表中去。

image

  

猜你喜欢

转载自blog.csdn.net/invoker123/article/details/77817116