如何在用户侧使用类似kernel中提供的list接口

29 篇文章 0 订阅
16 篇文章 0 订阅

Linux kernel linked list for user space

We can use Linux kernel linked list for user space with a very small modifications. It's a single header file. very handy!

Here is a recipe to fix list.h for user space program.

  1. Get linux/include/list.h
  2. Remove
    • #ifdef __KERNE__ and its #endif
    • all #include line
    • prefetch(something)
    • rcu related functions(many of them there)
  3. Add
    • A macro offsetof()
    • A macro container_of()

You can get a modified header file(list.h) from here.

A sample program
#include <stdio.h>
#include <stdlib.h>
#include "list.h"

struct a_list
{
  struct list_head list;
  int   val;
  const char* str;
};

static void append(struct a_list* ptr,const char* str, int val)           
{
  struct a_list* tmp;
  tmp = (struct a_list*)malloc(sizeof(struct a_list));
  if(!tmp) {
    perror("malloc");
    exit(1);
  }
  tmp->str = str;
  tmp->val = val;
  list_add_tail( &(tmp->list), &(ptr->list) );
}

int main()
{
  struct a_list  blist;
  struct a_list* iter; 

  INIT_LIST_HEAD(&blist.list);
  
  /* add item to list */
  append(&blist, "NM", 87501);
  append(&blist, "CA", 94041);
  append(&blist, "IL", 60561);

  /* iterates list */
  list_for_each_entry(iter,&blist.list,list) {
    printf("%s %d\n", iter->str, iter->val);
  }

  /* remove all items in the list */
  while( !list_empty(&blist.list) ) {
    iter = list_entry(blist.list.next,struct a_list,list);
    list_del(&iter->list);
    free(iter);
  }
  
  return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值