Linux kernel linked list for enterprise-level applications of linked list

In the Linux kernel, there are a large number of data structures that need to use doubly linked lists, such as processes, files, modules, pages, and so on. If the traditional implementation of a doubly linked list is adopted, it is necessary to maintain respective linked lists for these data structures, and to design insert, delete and other operation functions for each linked list. Because the next and prev pointers used to maintain the linked list point to the corresponding type of object, the linked list operation function of one data structure cannot be used to manipulate the linked list of other data structures. For example, we need to define the linked list structure of stars and web server timeouts respectively:

So how do we use the solution is to share the linked list:
the form of the shared linked list is like this:
typedef struct _DoubleLinkNode { struct _DoubleLinkNode *next; //The pointer field of the next node struct _DoubleLinkNode *prev;//The pointer field of the previous node }DbLinkNode; //The linked list is placed on the data as a hanging point //Clock hanging point typedef struct _ConnTimeout{ int fd; time_t timeout; NodeList d;








}ConnTimeout;
//星载挂点
typedef struct _START{
int x;
int y;
int r;
int step;
int statu;
NodeList d;
}START;

A small demo as follows:

/*
	linux内核链表,使用的原因是因为通过一个链表就能实现对多个数结构体的删除


*/

#include<stdio.h>
#include<Windows.h>
#include<iostream>
#include<stdlib.h>


using namespace std;

//结构体指针
typedef struct _DoubleList{
    
    
	_DoubleList *next;
	_DoubleList *prev;
}DoubleList,NodeList;

//时钟挂点
typedef struct _ConnTimeout{
    
    
	int fd;
	time_t timeout;
	NodeList d;
	
}ConnTimeout;

typedef struct _START{
    
    
	
	int x;
	int y;
	int r;
	int step;
	int statu;
	NodeList d;

}START;

//初始化链表
void init(DoubleList &L){
    
    
	
	if(!&L) return ;
	L.next = NULL;
	L.prev = NULL;

}

//插入元素
void insertElemdata(DoubleList &L,DoubleList &node){
    
    
	
	//找到最后一个结点

	if(!&L||!&node) return ;
	DoubleList *last = &L;
	
	while(last->next) last = last->next;

	node.next= NULL;
	node.prev=last;
	last->next = &node;

}

int main(void){
    
    

	ConnTimeout *t = new ConnTimeout;
	ConnTimeout *s =NULL;



	init(t->d);

	cout<<"请输入5个元素:"<<endl;
	for(int i=0;i<5;i++){
    
    

	//插入元素
	s = new ConnTimeout;
	cin>>s->fd;

	insertElemdata(t->d,s->d);
	}

	//计算偏移值
	int offset = offsetof(ConnTimeout,d);//获取偏移值
	DoubleList * p = &(t->d);
	while(p->next){
    
    
		p=p->next;
		ConnTimeout *ct = (ConnTimeout*)(size_t(p)-offset);
		cout<<ct->fd<<"\t";
		
	}


	//销毁链表
	printf("\n");
	p =&(t->d);
	//DoubleList *d;
	while(p){
    
    

		ConnTimeout *ct = (ConnTimeout*)(size_t(p)-offset);
		cout<<"删除结点"<<ct->fd<<endl;
		p=p->next;
		delete ct;

	}

	system("pause");
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45825875/article/details/115041609