-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlist.c
97 lines (79 loc) · 2.19 KB
/
list.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*
* @file list.c
* @details linux linked list DS
* @author smalinux <[email protected]>
*
*
* See also list2.c example
*
*/
#include <linux/module.h>
#include <linux/slab.h> //kmalloc()
MODULE_LICENSE("GPL");
struct person_t {
char * name;
int age;
struct list_head list; /* kernel's list structure */
} person_t;
/* Static allocate list head */
LIST_HEAD(person);
static int hello_init(void)
{
struct person_t *jack = kmalloc(sizeof(person_t), GFP_KERNEL);
struct person_t *luke = kmalloc(sizeof(person_t), GFP_KERNEL);
struct person_t *alex = kmalloc(sizeof(person_t), GFP_KERNEL);
struct person_t *mark = kmalloc(sizeof(person_t), GFP_KERNEL);
/* allocate memory for name field and fill every field */
jack->name = "Jack";
jack->age = 20;
luke->name = "Luke";
luke->age = 30;
alex->name = "Alex";
alex->age = 35;
mark->name = "Mark";
mark->age = 15;
/* Initialize each node's list entry */
INIT_LIST_HEAD(&jack->list);
INIT_LIST_HEAD(&luke->list);
INIT_LIST_HEAD(&alex->list);
INIT_LIST_HEAD(&mark->list);
/* add in the tail of list */
list_add_tail(&jack->list, &person);
/* add to the first element of list */
list_add(&luke->list, &person);
/* add element in between */
__list_add(&alex->list, &luke->list, &jack->list);
/* add element in between */
list_replace(&jack->list, &mark->list);
/* Take first element and move it to the last */
list_rotate_left(&person);
/* Get the fist entry */
struct person_t *last = list_last_entry(&person, struct person_t, list);
pr_info(": Last element is: %s\n", last->name);
/*
* Test APIs
* */
if(list_is_first(&luke->list, &person))
pr_info(": Yes, This is the fist.\n");
if(!list_empty(&person))
pr_info(": List is Not empty.\n");
if(!list_is_singular(&person))
pr_info(": List have more than single elment.\n");
// iterate over a list
struct person_t *counter;
int i = 0;
pr_cont("iterate over a list");
list_for_each_entry(counter, &person, list)
{
pr_info("node: Person %d name: %s, age: %d \n", ++i,
counter->name,
counter->age);
}
return 0;
}
static void hello_exit(void)
{
pr_err("Goodbye, cruel world\n");
}
module_init(hello_init);
module_exit(hello_exit);