linux内核学习:内核链表

版权声明:学习记录,积少成多 https://blog.csdn.net/changliang7731/article/details/53354005

数据结构是编程中很重要的一部分.链表是一种数据结构,编程中,我们为了实现链表这种数据结构,常常需要完成他的初始化,添加,遍历,添加,删除等功能.针对n多种链表来讲,除了内容不同外,但这些 添加,删除,遍历操作其实都是可以写成公共代码的,不必每次需要实现一种链表,就重新写一遍添加,删除,遍历的操作,太浪费时间和经历,且容易出错.幸运的是,内核有帮我们实现了这种功能,我们只需安心服用便可!

#include <linux/init.h>
#include <linux/module.h>
#include <linux/list.h>
#include <linux/kernel.h>
#include <asm/uaccess.h>
#include <linux/slab.h>
#include <linux/fs.h>


#define EMPLOYEE_NUM            5


static struct list_head employee_head;

static struct list_head *employee_pos = NULL;

struct employee{
    char name[20];
    int number;
    int salary;
    struct list_head list;
};

static struct employee *Pemployee = NULL;
static struct employee *Pemployeetmp = NULL;
static int __init list_init(void)
{
    int i;
    INIT_LIST_HEAD(&employee_head);

    Pemployee = kzalloc(sizeof(struct employee)*EMPLOYEE_NUM,GFP_KERNEL);
    if(Pemployee == NULL)
    {
        return -ENOMEM;
    }
    for(i=0;i<EMPLOYEE_NUM;i++)
    {

        sprintf(Pemployee[i].name,"Employee-%d",i+1);
        Pemployee[i].number =100+i;
        Pemployee[i].salary =20000 +1000*i;
        list_add(&(Pemployee[i].list),&employee_head);
    }

    list_for_each(employee_pos,&employee_head)
    {
        Pemployeetmp = list_entry(employee_pos,struct employee,list);
        printk(KERN_ALERT "Employee name :%s,number :%d,salary:%d.\n",Pemployeetmp->name,Pemployeetmp->number,Pemployeetmp->salary);
    }




    return 0;
}


static void  list_exit(void)
{
    int i;
    for(i=0;i <EMPLOYEE_NUM;i++)
    {
        list_del(&(Pemployee[i].list));
    }
    kfree(Pemployee);
}


module_init(list_init);
module_exit(list_exit);
MODULE_LICENSE("GPL");

现象:

猜你喜欢

转载自blog.csdn.net/changliang7731/article/details/53354005