调用内核hlist编写的测试代码

来源:互联网 发布:百色教务网络管理系统 编辑:程序博客网 时间:2024/05/13 10:45
最近在做linux内核编程,最深的一点感触是:算法的巧妙,犹如看一场高明杂技
真正的程序员那是键盘上灵动的舞者。
写面写的是一个调用内核的hlist测试代码。
/***how to program use  the hlist in kernel**/#include<linux/module.h> #include<linux/init.h> /* kind of macros */#include<linux/kernel.h>#include<linux/types.h>#include<linux/list.h>#include<linux/slab.h>unsigned int len_hash = 100;struct hlist_head* hash[100];void get_random_bytes(void *buf,int nbytes);/* define the data strc */typedef struct _data_node{    unsigned int  data;    struct hlist_node node;} data_node_strc;/* init the hash-chain */void init_hash(void){  unsigned int i=0;  for(i=0;i<len_hash;i++)     {        hash[i] = (struct hlist_head*)kmalloc(sizeof(struct hlist_head),0);        memset(hash[i],0,sizeof(struct hlist_head));     }}/* get a random numer */unsigned int rand(unsigned int lower,unsigned int up){  unsigned int rand = 0;  get_random_bytes(&rand,sizeof(unsigned int ));  return (rand%(up-lower)+lower);}/* alloc the memory */data_node_strc* kalloc_node(void){   data_node_strc* tmp = (data_node_strc*)kmalloc(sizeof(data_node_strc),0);   memset(tmp,0,sizeof(data_node_strc));   return tmp;   }/* full the hash-chain randomly */void full_hash(void){   int i = 0;   for(i=0;i<100;i++)      {        unsigned int key = rand(0,100);        data_node_strc* p_node = kalloc_node();        p_node->data = key;        hlist_add_head(&(p_node->node),hash[key]);      }}void print_hash(void){  unsigned int i = 0;  for(i=0;i<len_hash;i++)      {       if(!hlist_empty(hash[i]))         {           data_node_strc * tmp = NULL;           struct hlist_node *tmp_node = NULL;           int j=0;           hlist_for_each_entry(tmp,tmp_node,hash[i],node)                                {                                  printk("(key=%d,node=%d)->data=%d\n",i,j,tmp->data);                                  j++;                                }         }     }}void free_hash(void){  int i = 0;   for(i=0;i<len_hash;i++)      {        if(!hlist_empty(hash[i]))           {           data_node_strc * tmp = NULL;                      struct hlist_node * tmp_node = NULL ;           hlist_for_each_entry(tmp,tmp_node,hash[i],node)                                {                                  tmp->node.next = NULL;                                  tmp->node.pprev = NULL;                                  kfree(tmp);                                }           hash[i]->first = NULL;                     }        kfree(hash[i]);        hash[i] = NULL;       }}/* init the module */static int __init hlist_init(void){   init_hash();   full_hash();   print_hash();   return 0;}/* exit the module */static void __exit hlist_exit(void){   free_hash();}/* call the macro module_init() to init the module*/module_init(hlist_init);/* call the macro module_exit() to init the module*/module_exit(hlist_exit);/* obey the GPL poc */MODULE_LICENSE("GPL");MODULE_AUTHOR("dead_angel");MODULE_DESCRIPTION("timer_test");


原创粉丝点击