Let’s build our first simple driver. The HelloWorld driver.

This is the code of the HelloWorld driver.

This is the .C code for the HelloWorld driver. When you insmod the driver, “Hello World!” will print. and when you rmmod the driver, “Good Bye” will print. Since this is a Linux driver file or Kernel module, we have to include <linux/init.h> and <linux/module.h>. We do not include stdio.h or other C libraries because the Linux kernel does not have these stranded C libraries.


We can define the license of the driver with the command MODULE_LICENSE.  


We cant use printf to print lines on the kernel. We have to use printk. This is because we do not use the standers C libraries. we use the kernel libraries and the kernel has printk to print lines. Also, we can change what type of msg we are going to print in printk by setting the keyword KERN_ALERT. KERN_ALERT means that it is an alert. we can change it to any type like KERN_ERROR or etc.
Still, when you insmod and rmmod you can’t see where is this is printing. Because these prints are happening on the msg log. You can type `demsg` on the terminal and view the msg log and you can see the print out of printk.


Ok, now we need to compile the C code before running the code. To compile a kernel module we need to write a make file. The make file is like this for this helloworld.C file.

Save this file naming `Makefile` in the same directory as you saved the helloworld.C file. In the make file, # mark will be the comment mark and // in C code. now open the terminal at the saved file location and type `make` to build the kernel module.

If there are no errors, you will see there is a file called `helloworld.ko`. This is the kernal mdule we build.Now lets insmod the kernel module.
What is the word mean of insmod and rmmod? Insmod mean like installing the driver and rmmod mean removing the driver. you can install the driver by opening the terminal at the helloworl.ko file location and enter `sudo insmod helloworld.ko`. To remove the driver enter `sudo rmmod helloworld` in terminal. Form this way you can install a driver and remove a driver.

I think you have got some idea about how to make a simplest driver with Linux 🙂

***Please note that all of the content on this post was originally published on champlnx.blogspot.com. We have migrated these posts to www.champlnx.com for your convenience and continued access.

Leave a Reply

Your email address will not be published. Required fields are marked *