Linux-----单链表

Linux中实现链表

//定义链表节点结构体
struct Node{
  int data;//数据区
  struct Node* next;//指向下一个地址域
};
//初始化链表为空格
struct Node* head = NULL;
//插入元素到链表的末尾
void insert(int data){
sturct Node* newNode =(struct Node*)malloc(sizeof(struct Node));//根据链表节点结构体的大小分配堆空间,用来存放新的节点
newNode->data = data;
newNode->next = NULL;
if(head==NULL){
 head = newNode;//头结点
}else{
 struct Node* current = head;// 头结点指向第一个现有系欸但
 while(current->next!=NULL){
    current = current->next;
    }
  }
  current->next = newNode;
}
void printList(){
  struct Node* current = head;
  printf("Linked List");
  while(current!=NULL){
  printf("%d ->",current->data);
  current = current->next;
  }
printf("NULL\n");
}
int main(){
  insert(1);
  insert(2);
  insert(3);
 // 打印链表
    printList();

    // 释放链表内存
    struct Node* current = head;
    while (current != NULL) {
        struct Node* next = current->next;
        free(current);
        current = next;
    }

    return 0
}

内核中的链表

#include <linux/module.h> //包含了 Linux 内核模块开发所需的头文件
#include <linux/list.h> //包含了链表操作所需的头文件
#include <linux/kernel.h>//包含了内核开发所需的通用函数和宏。
#include <linux/slab.h>//包含了内存分配和释放相关的函数和宏

MODULE_LICENSE("GPL");

struct student {
    int id; //学号
    char name[20];//姓名
    struct list_head list;//用于将学生对象链接到链表中。
};

LIST_HEAD(student_list);//创建一个名为 student_list 的链表头,这是一个宏,实际上展开为一个包含链表头的结构体。
//定义内核模块的初始化函数,__init 表示这是一个在模块加载时执行的函数。
static int __init mymodule_init(void) {
    struct student *s;//声明一个指向学生结构体的指针

    // 添加元素到链表
    s = kmalloc(sizeof(struct student), GFP_KERNEL);//使用 kmalloc 函数分配内核内存以存储学生结构体,如果分配失败,会打印一条错误消息并返回 -ENOMEM  GFP_KERNEL 意味着内核可以在需要时等待内存分配成功。如果在当前没有足够的内存可用时,内核可能会通过等待来尝试获取内存,这可能导致当前进程被挂起(阻塞)直到内存可用
    if (!s) {
        printk(KERN_ALERT "Failed to allocate memory\n");
        return -ENOMEM;
    }
    s->id = 1;
    strcpy(s->name, "Alice");
    list_add(&s->list, &student_list);

    // 遍历链表并打印元素
    list_for_each_entry(s, &student_list, list) {
        printk(KERN_INFO "ID: %d, Name: %s\n", s->id, s->name);
    }

    return 0;
}

static void __exit mymodule_exit(void) {
    struct student *s, *tmp;

    // 释放链表中的内存
    list_for_each_entry_safe(s, tmp, &student_list, list) {
        list_del(&s->list);
        kfree(s);
    }
}

module_init(mymodule_init);
module_exit(mymodule_exit);

内核模块的入口点是** module_init** 宏指定的初始化函数,而不是传统的 main 函数。

posted @ 2023-09-28 20:26  不会笑的孩子  阅读(27)  评论(0编辑  收藏  举报