LoginSignup
2

More than 5 years have passed since last update.

list_headの小さなサンプルメモ

Last updated at Posted at 2017-09-18

前提

ubuntu# uname -a
Linux ubuntu 4.4.0-93-generic #116-Ubuntu SMP Fri Aug 11 21:17:51 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
ubuntu# cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=16.04
DISTRIB_CODENAME=xenial
DISTRIB_DESCRIPTION="Ubuntu 16.04.3 LTS"

仕組みはよく分かってないので、後から調べる。
とりあえずLinuxのコード読んでてよくわからなかったので、最小限の動くコードのみメモ(メモリの開放処理も無し)。

コード

kure.c
#include <linux/module.h>       /* MODULE, THIS_MODULE */
#include <linux/moduleparam.h>
#include <linux/kernel.h>       /* printk() */
#include <linux/errno.h>        /* error codes */
#include <linux/list.h>         /* list_*() */
#include <linux/slab.h>         /* kmalloc() */

MODULE_AUTHOR("kuredev");
MODULE_LICENSE("Dual BSD/GPL");

struct kurest
{
        int no;
        struct list_head list_head_;
};

struct kurest data1 = {
        .no = -1,
};

static int kure_init(void)
{
        printk(KERN_ALERT "Listtest init\n");
        struct kurest *data2, *data3;
        struct list_head *ptr;
        struct kurest *entry;
        INIT_LIST_HEAD(&data1.list_head_);

        data2 = kmalloc(sizeof(struct kurest), GFP_KERNEL);
        data2->no = 2;
        list_add(&data2->list_head_, &data1.list_head_);

        data3 = kmalloc(sizeof(struct kurest), GFP_KERNEL);
        data3->no = 3;
        list_add(&data3->list_head_, &data1.list_head_);

        list_for_each(ptr, &data1.list_head_){
                 entry = list_entry(ptr, struct kurest, list_head_);
                 printk("no: %d\n", entry->no);
        }

        return 0;
}


static void kure_exit(void)
{
        printk(KERN_ALERT "Listtest exit\n");
}

module_init(kure_init);
module_exit(kure_exit);
Makefile
KERNEL_DIR = /lib/modules/$(shell uname -r)/build
BUILD_DIR := $(shell pwd)
VERBOSE   := 0
obj-m := kure.o
all:
        make -C $(KERNEL_DIR) SUBDIRS=$(BUILD_DIR) KBUILD_VERBOSE=$(VERBOSE) modules
clean:
        rm -rf  *.o *.ko *.mod.c *.symvers *.order .tmp_versions .kure.*

実行

# make
# insmod kure.ko
# tail /var/log/syslog
Sep 18 23:12:16 ubuntu kernel: [23064.945863] Listtest init
Sep 18 23:12:16 ubuntu kernel: [23064.945869] no: 3
Sep 18 23:12:16 ubuntu kernel: [23064.945870] no: 2
Sep 18 23:12:21 ubuntu kernel: [23069.543457] Listtest exit

参考

linuxカーネルが提供するリストの使い方について - mmitouの日記 http://d.hatena.ne.jp/mmitou/20120626/1340731801

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2