操作系统使用linux的内核代码的具体例子
目标:创建一个birthday结构体,以链表形式连起来,顺序输出并倒置后删除
注:没有使用for结构体是不支持普通for循环结构,会自动报错出来的
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/list.h>
#include <linux/init.h>
#include <linux/types.h>
/*
In the module entry point, create a linked list containing five struct birthday
elements. Traverse the linked list and output its contents to the kernel log buffer.
Invoke the dmesg command to ensure the list is properly constructed once the
kernel module has been loaded.
In the module exit point, delete the elements from the linked list and return
the free memory back to the kernel. Again, invoke the dmesg command to check
that the list has been removed once the kernel module has been unloaded.
*/
struct birthday{
int day;
int month;
int year;
struct list_head list;
};
int my_init(void)
{
printk(KERN_INFO "Loading Module\n");
static LIST_HEAD(birthday_list);
struct birthday *person;
person = kmalloc(sizeof(*person),GFP_KERNEL);
person->day=2;
person->month=1;
person->year=1995;
INIT_LIST_HEAD(&person->list);
list_add_tail(&person->list,&birthday_list);
person = kmalloc(sizeof(*person),GFP_KERNEL);
person->day=2;
person->month=2;
person->year=1995;
INIT_LIST_HEAD(&person->list);
list_add_tail(&person->list,&birthday_list);
person = kmalloc(sizeof(*person),GFP_KERNEL);
person->day=2;
person->month=3;
person->year=1995;
INIT_LIST_HEAD(&person->list);
list_add_tail(&person->list,&birthday_list);
person = kmalloc(sizeof(*person),GFP_KERNEL);
person->day=2;
person->month=4;
person->year=1995;
INIT_LIST_HEAD(&person->list);
list_add_tail(&person->list,&birthday_list);
person = kmalloc(sizeof(*person),GFP_KERNEL);
person->day=2;
person->month=4;
person->year=1995;
INIT_LIST_HEAD(&person->list);
list_add_tail(&person->list,&birthday_list);
struct birthday *ptr;
list_for_each_entry(ptr,&birthday_list,list){
printk(KERN_INFO "year:%d month:%d day:%d\n",ptr->year,ptr->month,ptr->day);
}
return 0;
}
void my_exit(void) {
printk(KERN_INFO "Removing Module\n");
static LIST_HEAD(birthday_list);
struct birthday *ptr, *next;
list_for_each_entry_safe(ptr, next, &birthday_list, list){
list_del(&ptr->list);
kfree(ptr);
}
}
module_init( my_init );
module_exit( my_exit );
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("My Module");
MODULE_AUTHOR("SGG");