内核链表list的学习笔记(C)

一、实现将信息插入链表并打印

(1)定义及说明


struct list_head {
	struct list_head *next, *prev;
};

#define LIST_HEAD_INIT(name) { &(name), &(name) }

#define LIST_HEAD(name) \
	struct list_head name = LIST_HEAD_INIT(name)

static inline void INIT_LIST_HEAD(struct list_head *list)
{
	list->next = list;
	list->prev = list;
}

(2)将某文件夹下的所有文件部分相关信息插入内核list


// 主实现
struct list_head* get_file_list(const char *dir,struct list_head *head)
{
    struct dirent **namelist; // struct dirent * namelist[];
    struct file_t *node=  (struct file_t *)calloc(1, sizeof (struct file_t));
	if (!node){
		return NULL;
	}
	
	INIT_LIST_HEAD(&node->list); 
    
    chdir(dir);
    int count = scandir(dir, &namelist,sfilter, alphasort);
    if (count < 0) {
        perror("scandir error");
        goto Exit;  
    }
    int i = 0;
    for (i = 0; i < count; i++){
        memset(node, 0, sizeof(*node));
        struct dirent *entry = namelist[i];
        uint64_t timestamp=get_timestamp(namelist[i]->d_name);
        node->timestamp = timestamp;
        strcpy(node->total_path,dir);
        list_add_tail(&node->list,head);//尾插法
    }
    free(namelist);
    return head;
}  
Exit:
	free();   // 注意异常退出的释放  
	

(3)遍历此链表

// 遍历实现
list_for_each_entry(node,plist,list){
     printf("filelist:path = %s\n" ,node->total_path);
     printf("filelist:time = %ld\n",node->timestamp);
}

二、如何遍历链表并安全删除数据

(1)【list_for_each_entry_safe】定义及说明


/* @ 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);
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值