Table of Contents

Linux - Kernel - Kernel Drivers - Hello World

A basic Linux Kernel Driver.


Create a C program

vi hello.c

and populate as

hello.c
#include <linux/init.h>
#include <linux/module.h>
MODULE_LICENSE("Dual BSD/GPL");
 
static int hello_init(void)
{
  printk(KERN_ALERT "Hello, world\n");
  return 0;
}
 
static void hello_exit(void)
{
  printk(KERN_ALERT "Goodbye, cruel world\n");
}
 
module_init(hello_init);
module_exit(hello_exit);

Save the file.


Create a Makefile

vi Makefile

and populate as:

Makefile
# To build modules outside of the kernel tree, we run "make"
# in the kernel source tree; the Makefile these then includes this
# Makefile once again.
# This conditional selects whether we are being included from the
# kernel Makefile or not.
ifeq ($(KERNELRELEASE),)
 
    # Assume the source tree is where the running kernel was built
    # You should set KERNELDIR in the environment if it's elsewhere
    KERNELDIR ?= /lib/modules/$(shell uname -r)/build
    # The current directory is passed to sub-makes as argument
    PWD := $(shell pwd)
 
modules:
        $(MAKE) -C $(KERNELDIR) M=$(PWD) modules
 
modules_install:
        $(MAKE) -C $(KERNELDIR) M=$(PWD) modules_install
 
clean:
        rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versions
 
.PHONY: modules modules_install clean
 
else
    # called from kernel build system: just declare what our modules are
    obj-m := hello.o hellop.o
endif

Compile the module

make

displays:

make -C /lib/modules/4.15.0-72-generic/build M=/home/peter/prog/kernel/helloworld modules
make[1]: Entering directory '/usr/src/linux-headers-4.15.0-72-generic'
  Building modules, stage 2.
  MODPOST 1 modules
make[1]: Leaving directory '/usr/src/linux-headers-4.15.0-72-generic'

Check the module

ls hello,ko

displays:

hello.ko

Load the module

sudo insmod hello.ko

NOTE: This will not display anything.


Check if the module is loaded

lsmod

returns:

Module                  Size  Used by
hello                  16384  0
....

Check message from module

As mentioned above when the module was loaded it did not display that “Hello World” message.

This message is actually written to the system log.

tail /var/log/syslog

returns:

Dec 14 17:05:19 peter-bigmamba kernel: [74429.517770] Hello, world

Remove the module

sudo rmmod hello.ko