zoukankan      html  css  js  c++  java
  • 如何使用kernel中的list结构来保存自定义数据

    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;
    }
  • 相关阅读:
    hibernate中many-to-one的not-found属性和@notfound注解
    使用excel中的数据快速生成sql语句
    maven的生命周期
    单点登录(sso)入门
    sql server生成随机id
    javascript时间戳与日期格式的相互转换
    前后端分离的概念
    idea中maven项目打jar包
    [na][win]AD域组策略wifi自动配置
    [na]mail收发过程
  • 原文地址:https://www.cnblogs.com/smilingsusu/p/14634490.html
Copyright © 2011-2022 走看看