我正在为Linux内核编写程序,以实现链接列表并添加某些人的出生日期。添加它们之后,我需要找到最大使用期限并删除该节点。
为了找到具有最长使用期限的节点,我打算设置一个指向链表第一个元素的指针,并在进行迭代时比较使用期限。我不知道如何将最大指针设置为链接列表的开头。
我尝试了几种不同的方法,包括:
struct birthday * max = &birthday_list
struct birthday max = birthday_list
max = birthday_list.next;
错误我得到: error: assignment from incompatible pointer type [-Werror=incompatible-pointer-types]
我想我可能正在将列表分配给其他结构。我可以弄清楚我可能做错了什么吗?
#include<linux/list.h>
#include<linux/init.h>
#include<linux/kernel.h>
#include<linux/module.h>
#include<linux/types.h>
#include<linux/slab.h>
struct birthday {
int day;
int month;
int year;
struct list_head list;
}
static LIST_HEAD(birthday_list);
static void remove_oldest_student(void){
struct birthday *max, *curr, *next;
//point max to list head
max = LIST_HEAD(birthday_list);
list_for_each_entry(curr, &birthday_list, list){
//find_max(&max, &curr);
}
printk(KERN_INFO "Oldest Student Details --> Name: %s, Month: %d, Day: %d, Year: %d\n",max->name, max->month,max->day,max->year);
}
int simple_init(void) {
struct birthday *ptr;
int i;
for(i = 0; i < 5; i++) {
// create 5 birthday structs and add them to the list
struct birthday *person;
person = kmalloc(sizeof(*person), GFP_KERNEL);
person->day = 22;
person->month = 11;
person->year = 1981;
INIT_LIST_HEAD(&person->list);
list_add_tail(&person->list, &birthday_list);
}
list_for_each_entry(ptr, &birthday_list, list) {
// print the info from the structs to the log
printk(KERN_INFO "%d, %d %d", ptr->month, ptr->day, ptr->year);
}
remove_oldest_student();
return 0;
}
void simple_exit(void) {
struct birthday *ptr, *next;
list_for_each_entry_safe(ptr, next, &birthday_list, list) {
// delete structs and return memory
list_del(&ptr->list);
kfree(ptr);
}
}
module_init(simple_init);
module_exit(simple_exit);
我打算设置一个指向链表第一个元素的指针
只需使用list_first_entry
宏:
max = list_first_entry(&birthday_list, struct birthday, list);
提示:由于您已经有指向第一个元素的指针,因此无需在以下循环中对其进行迭代。代替list_for_each_entry
您可以使用list_for_each_entry_continue
:
// Make iterator to point to the already located element (first element in the list)
curr = max;
// Continue iteration.
// So the first iterated element will be the second element in the list
list_for_each_entry_continue(curr, &birthday_list, list){
//find_max(&max, &curr);
}