Linux内核list链表学习(一)--- list_for_each_entry_safe
程序员文章站
2024-01-23 16:19:22
...
【说明】学习Linux内核list链表,利用list.h中函数实现某些功能,直接上整理;
一、list_for_each_entry_safe — 遍历整个链表,安全地组织删除表中元素
(1)定义及说明
/* @ pos: 用作循环光标的类型*
* @ n: 另一种类型*用作临时存储
* @ head: 链表list的头节点
* @ member: struct中list_struct的名称 */
#define list_for_each_entry_safe(pos, n, head, member) \
for (pos = list_entry((head)->next, typeof(*pos), member), \
n = list_entry(pos->member.next, typeof(*pos), member); \
&pos->member != (head); \
pos = n, n = list_entry(n->member.next, typeof(*n), member))
(2)代码应用示例
// struct结构请根据需求填写,此处只是随意举例
struct offset {
struct list_head list;
int off_set;
off_t pos;
};
struct task_stat {
struct list_head list;
pthread_t thid;
int sockfd;
int timeout;
int port;
struct list_head offsets; /* list of struct offset */
};
void free_stat(struct task_stat* stat)
{
struct offset *off, *off_tmp;
if (!stat){
return;
}
list_for_each_entry_safe(off, off_tmp, &stat->offsets, list) {
list_del(&off->list);
free(off);
}
free(stat);
}