數據結構是編程中很重要的一部分.鏈表是一種數據結構,編程中,我們爲了實現鏈表這種數據結構,常常需要完成他的初始化,添加,遍歷,添加,刪除等功能.針對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");
現象: