Skip to main content

Kernel Driver

Linux does not allow to directly access hardware from userspace. Thats why a driver is needed. Read below how to write one.

Prerequisites

sudo apt install linux-headers-$(uname -r)
Makefile
obj-m += my-driver.o
KDIR = /lib/modules/$(shell uname -r)/build

all:
make -C $(KDIR) M=$(shell pwd) modules

clean:
make -C $(KDIR) M=$(shell pwd) clean

Basic Hello World Driver

my-driver.c
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>

static int __init my_driver_init(void) {
printk("Welcome to my driver!\n");
return 0;
}

static int __exit my_driver_exit(void) {
printk("Leaving my driver!\n");
return;
}

module_init(my_driver_init);
module_exit(my_driver_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("<author>");
MODULE_DESCRIPTION("My Driver");
MODULE_VERSION("1.0");

To see the output run:

dmesg

User interface for the driver

my-driver.c

Source