#include <linux/init.h>
#include <linux/module.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <linux/kernel.h>
struct list_head head;
struct student
{
int num;
char name[30];
struct list_head list;
};
static int __init listtest_init(void)
{
INIT_LIST_HEAD(&head);
struct student *node_p = NULL;
int i;
//链表的创建
for(i=0; i<10; i++)
{
node_p = kmalloc(sizeof(struct student),GFP_KERNEL);
if(IS_ERR(node_p))
{
goto fail_malloc;
}
node_p->num = i;
sprintf(node_p->name,"studentname%d",i);
list_add(&(node_p->list),&head);
}
//遍历链表
struct list_head *tmp = NULL;
list_for_each(tmp,&head)
{
node_p = list_entry(tmp,struct student,list);
printk("student num: %d \t name: %s\n",node_p->num,node_p->name);
}
#if 0
list_for_each_entry(onep,&head,list)
{
printk("student num: %d \t name: %s\n",onep->num,onep->name);
}
#endif
struct list_head *next_p;
list_for_each_safe(tmp,next_p,&head)
{
node_p = list_entry(tmp,struct student,list);
if(node_p->num == 6)
{
list_del(&node_p->list);
kfree(node_p);
}
}
list_for_each(tmp,&head)
{
node_p = list_entry(tmp,struct student,list);
printk("student num: %d \t name: %s\n",node_p->num,node_p->name);
}
return 0;
fail_malloc:
kfree(node_p);
}
static void __exit listtest_exit(void)
{
return ;
}
module_init(listtest_init);
module_exit(listtest_exit);
MODULE_LICENSE("GPL");