首页 > 其他 > 详细

如何使用kernel中的list结构来保存自定义数据

时间:2021-04-08 20:41:07      阅读:21      评论:0      收藏:0      [点我收藏+]

 

1.首先定义自己所需的结构体。

struct my_mapping_struct {
    struct list_head list;
    int file;
    void *virt;
    struct my_data *md;
}

 

2.定义并初始化一个全局的list head与一把mutex。

static DEFINE_MUTEX(my_mutex);
static LIST_HEAD(my_list_head);

 

3.向list head中添加新元素。

static int my_list_add(int file, void *virt, struct my_data *md)
{
    struct my_mapping_struct *node;
    node = kmalloc(sizeof(struct my_mapping_struct), GFP_KERNEL);
    if (!node)
        return -NOMEM;
    node->file = file;
    node->virt = virt;
    node->md   = md;
    mutex_lock(&my_mutex);
    list_add(&node->list, &my_list_head);
    mutex_unlock(&my_mutex);

    return 0;
}

 

4.向list head中删除指定md元素。

static int my_list_del(struct my_data *md)
{
    struct list_head *pos;
    struct my_mapping_struct *node;
    int is_found = 0;
    
    mutex_lock(&my_mutex);
    list_for_each(pos, &my_list_head) {
        node = container_of(pos, struct my_mapping_struct, list);
        if (node->md == md) {
            list_del(&node->list);
            kfree(node);
            is_found = 1;
            break;
        }
    }
    mutex_unlock(&my_mutex);
    return is_found?0:1;
}

 

5.在list head中查找特定md的元素。

static struct my_data *my_find_node(void *virt)
{
    struct list_head *pos;
    struct my_mapping_struct *node;
    struct my_data *md = NULL;
    
    mutex_lock(&my_mutex);
    list_for_each(pos, &my_list_head) {
        node = container_of(pos, struct my_mapping_struct, list);
        if (node->virt == virt) {
            md = node->md;
            break;
        }
    }
    mutex_unlock(&my_mutex);
    
    return md;
}

 

如何使用kernel中的list结构来保存自定义数据

原文:https://www.cnblogs.com/smilingsusu/p/14634490.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!