/*准备工作: 修改makefile文件 修改 printk输出级别*/
#include
#include
#include
#include
MODULE_LICENSE("GPL");
MODULE_AUTHOR("XIYOU"); //模块的所有者;
#define N 10 //链表节点
struct numlist { //定义含有数据域的链表;
int num; //数据
struct list_head list;//指向双链表前后节点的指针 list域隐藏了链表的指针特性struct list_head可以位于结构的任何位置,可以给其起任何名字
};
struct numlist numhead;//头节点
static int __init doublelist_init(void)
{
//初始化头节点
struct numlist *listnode;//每次申请链表节点时所用的指针
struct list_head *pos; //定义一个指针变量指向当前节点;
struct numlist *p; // 用来保存当前数据节点的首地址,即指针
int i; //定义局部变量i;
printk("doublelist is starting...\n"); //打印程序开始信息;
INIT_LIST_HEAD(&numhead.list); //用函数初始化空链表;
//建立N个节点,依次加入到链表当中
for (i = 0; i < N; i++) {
listnode = (struct numlist *)kmalloc(sizeof(struct numlist), GFP_KERNEL); // kmalloc() 在内核空间申请内存
listnode->num = i+1; //给胖节点数据域依次赋值;
list_add_tail(&listnode->list, &numhead.list); //该函数向指定链表的head节点前插入新的节点;
printk("<0> Node %d has added to the doublelist...\n", i+1); //打印添加节点信息;
}
//遍历链表
i = 1;
list_for_each(pos, &numhead.list) {
p = list_entry(pos, struct numlist, list); //指针pos指向结构体numlist中的成员num;通过指针pos,返回结构体numlist的起始地址,也就是list_entry返回指向numlist类型的指针
printk("<0> Node %d's data:%d\n", i, p->num); //将每个节点的数据打印出来;printk输出为最高级别;
i++;
}
return 0;
}
static void __exit doublelist_exit(void) /*模块卸载函数*/
{
struct list_head *pos, *n;
struct numlist *p; // 用来保存获得结构体numlist首地址;
int i;
//依次删除N个节点
i = 1;
list_for_each_safe(pos, n, &numhead.list) { //为了安全删除节点而进行的遍历
list_del(pos);//从双链表中删除当前节点
p = list_entry(pos, struct numlist, list);//得到当前数据节点的首地址,即指针
kfree(p);//释放该数据节点所占空间
printk("Node %d has removed from the doublelist...\n", i++);
}
printk("doublelist is exiting..\n");
}
module_init(doublelist_init); //模块加载函数;
module_exit(doublelist_exit); //模块卸载函数;
/*运行过程:
[root@bogon list]# make
make -C /usr/src/kernels/2.6.32-71.el6.i686 M=/root/桌面/list modules
make[1]: Entering directory `/usr/src/kernels/2.6.32-71.el6.i6............
.......
[root@bogon list]# insmod doublelist.ko
essage from syslogd@localhost at Oct 9 08:03:02 ...
kernel: Node 1's data:1
Message from syslogd@localhost at Oct 9 08:03:02 ...
kernel: Node 2's data:2
阅读(1951) | 评论(0) | 转发(0) |