【问题标题】:List.h in linux files?Linux文件中的List.h?
【发布时间】:2021-07-31 04:20:16
【问题描述】:

在 linux/include/linux/list.h 我发现:

/**
 * list_entry - get the struct for this entry
 * @ptr:    the &struct list_head pointer.
 * @type:   the type of the struct this is embedded in.
 * @member: the name of the list_head within the struct.
 */
#define list_entry(ptr, type, member) \
    container_of(ptr, type, member)

“获取此条目的结构”是什么意思,我可以看一个用法示例以更好地理解吗?

【问题讨论】:

  • 定义了一个宏,它调用具有相同参数的函数。

标签: c linux list unix


【解决方案1】:

这是 C 中一种多态性的一个很好的例子。借用 C++ 的术语,list_entry() 宏允许您从 list_head 类型向上转换为包含它的任何类型。

查看kthread.c 以获得一个简单的基本示例:

内核/kthread.c:

struct kthread_create_info
{
    /* Information passed to kthread() from kthreadd. */
    int (*threadfn)(void *data);
    void *data;
    int node;

    /* Result passed back to kthread_create() from kthreadd. */
    struct task_struct *result;
    struct completion *done;

    struct list_head list;
};

...
int kthreadd(void *unused)
{
...
        while (!list_empty(&kthread_create_list)) {
            struct kthread_create_info *create;

            create = list_entry(kthread_create_list.next,
                        struct kthread_create_info, list);
...
            create_kthread(create);

通过在kthread_create_info 结构中包含list_head 对象,您可以说kthread_create_info“派生”自list_head。这允许kthread_create_info 对象用作列表中的节点,这意味着您可以通过简单地取消引用结构的list 成员将它们传递给list.h 中声明的任何函数。 list_entry 宏然后为您提供从基类指针到其派生起始地址的映射。

换句话说,给定一个您知道包含在外部kthread_create_info 结构中的list_head 对象,您可以恢复指向kthread_create_info 容器的指针。

这是 C 编程中极为常见的模式,需要面向对象的构造,但 C++ 编译器不可用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-02
    • 1970-01-01
    • 2011-06-25
    • 2010-12-20
    • 2011-08-30
    • 1970-01-01
    • 1970-01-01
    • 2013-06-05
    相关资源
    最近更新 更多