LoginSignup
7
1

More than 5 years have passed since last update.

シンプルなキャラクタ型デバイスドライバ作成メモ

Posted at

前提

  • 実行後にログを出力するだけのデバイスドライバ
  • register_chrdevを使用(カーネル2.6系以降は推奨されないらしい)
  • Ubuntu 16.04、Windows/VMWare
  • Linux ubuntu 4.4.0-91-generic #114-Ubuntu SMP Tue Aug 8 11:56:56 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
  • エラーハンドリングは無し

メモ

コード

simple_kernelmodule.c
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/fs.h>

#define NODE_NAME "kuredev"
#define SUCCESS 0

MODULE_LICENSE("Dual BSD/GPL");

static int major_num = 0;

static int kure_open(struct inode *inode, struct file *file){
        printk("kure_open\n");
        return SUCCESS;
}

static int kure_release(struct inode *inode, struct file *file){
        printk("kure_release\n");
        return SUCCESS;
}

static ssize_t kure_read(struct file *file, char __user *buf, size_t count, loff_t *f_pos){
        printk("kure_read\n");
        return count;
}

static ssize_t kure_write(struct file *file, char __user *buf, size_t count,loff_t *f_pos){
        printk("kure_write\n");
        return count;
}

struct file_operations kure_fops = {
        .owner = THIS_MODULE,
        .read = kure_read,
        .write = kure_write,
        .open = kure_open,
        .release = kure_release
};

static int kure_init(void){
        major_num = register_chrdev(major_num, NODE_NAME, &kure_fops);
        printk("kure_init\n");
        return SUCCESS;
}

static void kure_exit(void){
        unregister_chrdev(major_num, NODE_NAME);
        printk("kure_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 := simple_kernelmodule.o
all:
        make -C $(KERNEL_DIR) SUBDIRS=$(BUILD_DIR) KBUILD_VERBOSE=$(VERBOSE) modules
clean:
        rm -rf  *.o *.ko *.mod.c *.symvers *.order .tmp_versions .helloworld.*

実行結果

# make
# insmod simple_kernelmodule.ko
# cat /proc/devices | grep kure
246 kuredev
# mknod -m 666 /dev/kuredev c 246 0
# echo 0 > /dev/kuredev
# rmmod simple_kernelmodule

実行結果(syslog)

Aug 13 05:14:01 ubuntu kernel: [ 9907.393185] kure_init ★insmod
Aug 13 05:15:11 ubuntu kernel: [ 9978.162543] kure_open ★echo 
Aug 13 05:15:11 ubuntu kernel: [ 9978.162552] kure_write
Aug 13 05:15:11 ubuntu kernel: [ 9978.162554] kure_release
Aug 13 05:15:35 ubuntu kernel: [10002.117217] kure_exit ★rmmod

参考

7
1
0

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
7
1