学习文档路径:
https://www.cnblogs.com/watson/p/3593237.html
内核源码路径:
/usr/src/kernels/3.10.0-123.el7.x86_64/include/linux/list.h
函数原型:
list_for_each_entry_safe(pos, n, head, member)
参数含义:
pos:the type * to use as a loop cursor. 定义一个结构指针,给该函数用
n:another type * to use as temporary storage 再定义一个结构指针,给该函数用
head:the head for your list. 指针头
member:the name of the list_struct within the struct 结构中的list_head名称
遍历链表例子:
typedef struct ceph_pool_lists
{
list_head list;
char total[CEPH_BUFF_LEN_L];
char free[CEPH_BUFF_LEN_L];
char used[CEPH_BUFF_LEN_L];
char type[CEPH_BUFF_LEN_L];
char mode[CEPH_BUFF_LEN_L];
char name[CEPH_BUFF_LEN_L];
}CEPH_POOL_LISTS;
static int cli_ceph_get_pool_list(list_head * outbuffer)
{
CEPH_POOL_LISTS *body = NULL;
CEPH_POOL_LISTS *body_next = NULL;
if (NULL != outbuffer){
list_for_each_entry_safe(body, body_next, outbuffer, list){
printf("name:%s\n", body->name);
printf("total:%s\n", body->total);
printf("free:%s\n", body->free);
printf("used:%s\n", body->used);
printf("type:%s\n", body->type);
printf("mode:%s\n", body->mode);
printf("\n");
bn_list_del(&body->list);
free(body);
body = NULL;
}
free(outbuffer);
outbuffer = NULL;
}
return 0;
}
组装链表例子:
int get_ceph_pool_list(void *inbuffer,void **outbuffer)
{
CEPH_POOL_LISTS *all_head[CEPH_BUFF_LEN_L] = {NULL}; //1、定义一个结构指针数组
list_head *sys_head = NULL; //2、定义一个头
CEPH_POOL_LISTS *pool_list_info = NULL; //3、定义一个结构指针
sys_head = (list_head *)malloc(sizeof(list_head)); //4、给头分配空间
if(!sys_head){
return 1;
}
memset(sys_head, 0, sizeof(list_head));
bn_list_init(sys_head); //5、清空并、初始化头指针
if((fp = fopen(CEPH_POOL_DETAIL_INFO,"r"))){
while(fgets(buff,sizeof(buff),fp)){
if(!get_pool_name_mode(buff,pool_name,mode)){
pool_list_info = (CEPH_POOL_LISTS *)malloc(sizeof(CEPH_POOL_LISTS)); //6、循环申请内存,并填充值
if(!pool_list_info){
return 1;
}
strcpy(pool_list_info->name,pool_name);
strcpy(pool_list_info->mode,mode);
all_head[pool_num] = pool_list_info; //7、将指针记录下来
pool_num++;
}
}
fclose(fp);
fp = NULL;
}
for(i=0; i<pool_num; i++){
bn_list_add(sys_head,&(all_head[i]->list)); //8、添加到链表中
}
*outbuffer = (void *)sys_head; //9、把链表头传出去
return 0;
}