zoukankan      html  css  js  c++  java
  • Linux 中list_head 如何使用

    源代码:

     1 #include <linux/module.h>
    2 #include <linux/init.h>
    3 #include<linux/sched.h>
    4 #include<linux/sem.h>
    5 #include <linux/slab.h>
    6 #include <linux/list.h>
    7
    8 MODULE_LICENSE("Dual BSD/GPL");
    9
    10 struct group{
    11 int id;
    12 char character;
    13 struct list_head member;
    14 };
    15
    16
    17 int list_head_init(void)
    18 {
    19 printk("list_head init\n");
    20
    21 struct group testhead={
    22 .id=-1,
    23 .character='a',
    24 .member=LIST_HEAD_INIT(testhead.member),
    25 };
    26
    27 //插入10个元素
    28 int i=0;
    29 for(i=0;i<10;i++)
    30 {
    31 struct group *testtemp;
    32 testtemp=kmalloc(sizeof(struct group),GFP_KERNEL);
    33 if(testtemp==NULL) return -1;
    34 testtemp->id=i;
    35 testtemp->character=(char)(64+i);
    36 list_add(&testtemp->member,&testhead.member);
    37 //printk(KERN_ALERT"%d--->%c\n",testtemp->intdata,testtemp->chardata);
    38 }
    39
    40
    41 //遍历10个元素
    42 struct group *groups,*p;
    43 struct list_head *pos;
    44 int count=0;
    45 printk(KERN_ALERT"Hello World enter begin:\n");
    46 groups=&testhead;
    47 list_for_each(pos,&groups->member)
    48 {
    49 p=list_entry(pos, struct group, member);
    50 count++;
    51 printk(KERN_ALERT"id is %d---> name %c\n",p->id,p->character);
    52 }
    53 printk(KERN_ALERT"the member of group is:%d\n",count);
    54
    55 //删除元素
    56 list_del(&p->member);
    57 count=0;
    58
    59 //遍历剩余元素
    60 list_for_each(pos,&groups->member)
    61 {
    62 p=list_entry(pos, struct group, member);
    63 count++;
    64 printk(KERN_ALERT"id is %d---> name %c\n",p->id,p->character);
    65 }
    66 printk(KERN_ALERT"the member of group is:%d\n",count);
    67
    68 return 0;
    69 }
    70 static void list_head_exit(void)
    71 {
    72 printk("list_head exit\n");
    73 }
    74
    75 module_init(list_head_init);
    76 module_exit(list_head_exit);
    77

    Makefile :

    1 obj-m := list_head.o
    2 KERNELDIR := /lib/modules/$(shell uname -r)/build
    3 PWD := $(shell pwd)
    4 modules:
    5 $(MAKE) -C $(KERNELDIR) M=$(PWD) modules
    6 modules_install:
    7 $(MAKE) -C $(KERNELDIR) M=$(PWD) modules_install
    8 clean:
    9 rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versions $(TARGET)

    运行命令:

    1 root@lab:sudo su
    2 root@lab:make
    3 root@lab:insmod list_head.ko
    4 root@lab:dmesg
    5 root@lab:rmmod list_head.ko





  • 相关阅读:
    MySQL优化
    MySQL 的 SQL 操作
    笔记本电脑同时使用两个网络
    top
    logrotate
    正则表达式学习总结
    HttpClient parameter 和body 传输同时进行
    Node.js背景
    前后端分离的理解
    shiro 的subject 以及Context 对象的具体的含义。
  • 原文地址:https://www.cnblogs.com/changefuture/p/2336989.html
Copyright © 2011-2022 走看看