Home / Learn Chip Programming / Linux Kernel Modules and Character Drivers

Linux Kernel Modules and Character Drivers

Write a loadable kernel module that creates a device you can read and write.

In shortWrite a loadable kernel module that creates a device you can read and write.

Theory in plain words

User to hardwareapp: write(fd, "1")VFSdriver .write()toggles GPIO register
User to hardware

What it is

A kernel module is code loaded into the kernel at runtime with insmod. A character driver registers file operations (open, read, write, ioctl) so user programs access hardware via /dev nodes.

Why we use it

Drivers hide hardware details behind standard file calls. Employers value driver knowledge for custom hardware.

How it works

module_init/module_exit, register a misc device, implement read/write that copy_to_user / copy_from_user, build with a Kbuild Makefile against the kernel headers.

Where it is used

  • Custom FPGA or sensor drivers
  • GPIO LED driver
  • Learning kernel internals

Mini character device

Simulate /dev/mycharTry it Yourself

This is the whole idea: user space talks to a file, the driver turns file operations into hardware or memory operations.

Minimal character driver (misc device)
#include <linux/module.h>
#include <linux/miscdevice.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
static char kbuf[64]; static size_t klen;
static ssize_t my_read(struct file *f, char __user *u, size_t n, loff_t *off) { return simple_read_from_buffer(u, n, off, kbuf, klen); }
static ssize_t my_write(struct file *f, const char __user *u, size_t n, loff_t *off) { klen = min(n, sizeof kbuf); if (copy_from_user(kbuf, u, klen)) return -EFAULT; return n; }
static const struct file_operations fops = { .owner = THIS_MODULE, .read = my_read, .write = my_write };
static struct miscdevice mdev = { .minor = MISC_DYNAMIC_MINOR, .name = "mychar", .fops = &fops };
static int __init my_init(void) { return misc_register(&mdev); }
static void __exit my_exit(void) { misc_deregister(&mdev); }
module_init(my_init); module_exit(my_exit); MODULE_LICENSE("GPL");
Careful:Never dereference a user pointer directly in the kernel. Use copy_to_user / copy_from_user and always check their return values. A bug in a driver crashes the whole system (kernel oops).

Quick quiz

1. How to load a module?

2. Why copy_from_user?

Common questions

How to load a module?

insmod or modprobe. Loads into the running kernel.

Why copy_from_user?

User pointers cannot be trusted or used directly. It safely copies from user space.