Linux kernel link list instance

I will focus on the code implementation to give a detail description. If you like, enjoy it.

#include <linux/module.h>
#include <linux/list.h>
#include <linux/err.h>
#include <linux/slab.h>
/* Create a link list head, its name is container_measurement */
/* The main data structure that you define to construct a link list */
struct container_entry{
	int container_id;
	int status;
	struct list_head later;

/*Create the link list node and add it to the previous link list by "LIST_HEAD()"*/
static struct container_entry *container_entry_create(int container_id, int status)
	struct container_entry *entry;
	entry = kmalloc(sizeof(*entry),GFP_KERNEL);
	if(entry == NULL){
		pr_err("OUT OF MEMORY ERROR creating container_entry\n");
		return -ENOMEM;
	entry->container_id = container_id;
	entry->status = status;
	return entry;
/*Lookup every link list node and find the node you want*/
static struct container_entry *container_entry_lookup(int container_id)
	struct container_entry *entry_p;
#if 0
	list_for_each(p, &container_measurement){
		entry_p = list_entry(p, struct container_entry,later);
		printk("Current: container_id:%d,status:%d\n", entry_p->container_id, entry_p->status);
	list_for_each_entry(entry_p, &container_measurement,later){
		printk("Current: container_id:%d,status:%d\n", entry_p->container_id, entry_p->status);
		if( entry_p->container_id == container_id ){
			printk("Success: %d:status:%d\n", entry_p->container_id, entry_p->status);
			return entry_p;
        return NULL;

/*Remove the node by its single value*/
int container_entry_del(int container_id)
	struct container_entry *entry_p;
	entry_p = container_entry_lookup(container_id);
	if(entry_p == NULL){
		printk("There is no container_id: %d\n", container_id);
		return -1;
	return 0;

/*kernel module init*/
static int __init hello_init(void)
	struct container_entry *entry;
	int id;
	id = 200;
	entry = container_entry_create(100,0);
	entry = container_entry_create(200,1);
	if ( container_entry_lookup(200) == NULL){

		printk("Sorry, container:%d does exist\n", id);
	return 0;

/*kernel module exit*/
static void __exit hello_exit(void)
	printk("hello,I am leaving\n");

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s