我正在为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);
我看到了几个问题,我确定这不是唯一的一个编译错误(例如max->name
-数据结构中没有这样的成员)。我也不想陷入逻辑错误,因为它与原始问题无关,这是典型的作业。让我们说清楚。似乎您正在尝试从包含在另一个struct对象(其成员)中的struct获取指针。可能是这样的:
max = container_of(birthday_list.next, struct birthday, list);
阅读有关container_of
的更多信息:SO post,nice guide,Linux kernel source
UPD:正如Tsyvarev在他的回答中提到的那样,有一个list
-API函数list_first_entry()
,该函数最终会调用list_first_entry()
。因此,如果您仍然[[确实需要该第一个条目-最好使用API函数。 container_of()
只是为了更好地了解发生了什么。
我打算设置一个指向链表第一个元素的指针
只需使用container_of()
宏:
container_of()
提示:由于您已经有一个指向第一个元素的指针,因此无需在以下循环中对其进行迭代。您可以使用list_first_entry
代替max = list_first_entry(&birthday_list, struct birthday, list);
:
list_for_each_entry