Linuxドライバを作成してみる

  • 投稿者:
  • 投稿カテゴリー:Linux

Linuxデバイスドライバ開発入門をやってみた

root@hostname:/home/shimizu/driver# cat /etc/debian_version
8.2
root@hostname:/home/shimizu/driver# uname -a
Linux hostname 3.16.0-4-amd64 #1 SMP Debian 3.16.7-ckt11-1+deb8u3 (2015-08-04) x86_64 GNU/Linux
root@hostname:/home/shimizu/driver# aptitude install linux-headers-3.16.0-4-amd64
...

root@hostname:/home/shimizu/driver# cat hello.c
#include <linux/module.h>
#include <linux/init.h>

MODULE_LICENSE("Dual BSD/GPL");

static int hello_init(void)
{
      printk(KERN_ALERT "driver loaded\n");
      printk(KERN_ALERT "Hello World\n");
      return 0;
}

static void hello_exit(void)
{
      printk(KERN_ALERT "driver unloaded\n");
}

module_init(hello_init);
module_exit(hello_exit);

root@hostname:/home/shimizu/driver# cat Makefile
obj-m := hello.o

all:
      make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

clean:
      make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

root@hostname:/home/shimizu/driver# make
make -C /lib/modules/3.16.0-4-amd64/build M=/home/shimizu/driver modules
make[1]: Entering directory '/usr/src/linux-headers-3.16.0-4-amd64'
Makefile:10: *** mixed implicit and normal rules: deprecated syntax
make[1]: Entering directory `/usr/src/linux-headers-3.16.0-4-amd64'
  CC [M]  /home/shimizu/driver/hello.o
  Building modules, stage 2.
  MODPOST 1 modules
  CC      /home/shimizu/driver/hello.mod.o
  LD [M]  /home/shimizu/driver/hello.ko
make[1]: Leaving directory '/usr/src/linux-headers-3.16.0-4-amd64'

root@hostname:/home/shimizu/driver# ls
Makefile  Module.symvers  hello.c  hello.ko  hello.mod.c  hello.mod.o  hello.o  modules.order

root@hostname:/home/shimizu/driver# insmod hello.ko
root@hostname:/home/shimizu/driver# lsmod | grep hello
hello                  12458  0

root@hostname:/home/shimizu/driver# rmmod hello
root@hostname:/home/shimizu/driver# lsmod | grep hello

### hello.cに記載している通り、モジュールロード時と削除時にsyslogに記載される ###
root@hostname:/home/shimizu/driver# tail -n 3 /var/log/syslog
Oct 25 17:29:44 hostname kernel: [4858346.340042] driver loaded
Oct 25 17:29:44 hostname kernel: [4858346.340050] Hello World
Oct 25 17:29:59 hostname kernel: [4858361.365712] driver unloaded