linux 内核list 排序示例
#include <linux/init.h>
#include <linux/module.h>
#include <linux/ktime.h>
#define log(fmt, args...) printk( KERN_ERR "%s.%d " fmt "", __FUNCTION__, __LINE__, ##args )
struct list_head g_oder_list_head;
typedef struct _list_node {
struct list_head node;
int data;
} list_node_t;
void dump_order_list(void)
{
list_node_t *item;
struct list_head *pos;
list_for_each(pos, &g_oder_list_head)
{
item = list_entry(pos, list_node_t, node);
log( "%d", item->data );
}
}
void order_list_add(list_node_t *new_item)
{
list_node_t *item;
struct list_head *pos;
struct list_head *nex;
list_for_each_safe( pos, nex, &(g_oder_list_head) )
{
item = list_entry( pos, list_node_t, node);
if ( new_item->data < item->data )
{
break;
}
}
list_add( &(new_item->node), pos->prev );
}
void order_list_del(list_node_t *item)
{
list_del( &(item->node) );
}
void order_list_destroy(void)
{
struct list_head *pos;
struct list_head *nex;
list_for_each_safe( pos, nex, &(g_oder_list_head) )
{
list_del(pos);
}
}
list_node_t t_item1;
list_node_t t_item2;
list_node_t t_item3;
list_node_t t_item4;
void test_add_items(void)
{
order_list_add( &t_item1 );
order_list_add( &t_item2 );
order_list_add( &t_item3 );
order_list_add( &t_item4 );
}
void test_case1(void)
{
t_item1.data = 1;
t_item2.data = 3;
t_item3.data = 5;
t_item4.data = 7;
test_add_items();
dump_order_list();
order_list_destroy();
}
void test_case2(void)
{
t_item1.data = 7;
t_item2.data = 5;
t_item3.data = 3;
t_item4.data = 1;
test_add_items();
dump_order_list();
order_list_destroy();
}
void test_case3(void)
{
t_item1.data = 5;
t_item2.data = 7;
t_item3.data = 1;
t_item4.data = 3;
test_add_items();
dump_order_list();
order_list_destroy();
}
void test_case4(void)
{
t_item1.data = 3;
t_item2.data = 7;
t_item3.data = 1;
t_item4.data = 5;
test_add_items();
dump_order_list();
order_list_destroy();
}
void test_case5(void)
{
t_item1.data = 3;
t_item2.data = 7;
t_item3.data = 1;
t_item4.data = 5;
test_add_items();
dump_order_list();
log("==========");
order_list_del( &t_item3 );
dump_order_list();
order_list_destroy();
}
typedef void(*test_case_func_t)(void);
test_case_func_t test_cases[] = {
test_case1,
test_case2,
test_case3,
test_case4,
test_case5
};
int list_oder_test_init(void)
{
int i = 0;
log("Test start");
INIT_LIST_HEAD(&g_oder_list_head);
for( i = 0; i < sizeof(test_cases)/sizeof(test_cases[0]); i++)
{
log( "case %d ++++++++++++++++++++", (i + 1 ));
test_cases[i]();
}
return 0;
}
void list_oder_test_exit(void)
{
log("Test end");
}
module_init(list_oder_test_init);
module_exit(list_oder_test_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("hrtimer test module");