Hello World Device Driver
hello_world.c:
#include<linux/module.h>
#include<linux/init.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("EMBEDDED GURUJI");
static int hello_init(void)
{
printk("Hello World\n");
return 0;
}
static void hello_exit(void)
{
printk("Bye World\n");
}
module_init(hello_init);
module_exit(hello_exit);
Makefile:
obj-m := hello_world.o
KERNELDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
all :
$(MAKE) -C $(KERNEL) M=$(PWD) modules
clean:
$(MAKE) -C $(KERNEL) M=$(PWD) clean
Now we will understand the code line by line
#include<linux/module.h>
#include<linux/init.h>
These header files contains the definition of the module_init() and module_exit() functions.
MODULE_LICENSE("GPL");
MODULE_LICENSE() informs the kernel the license used by the source code,which will affect the functions it can access from the kernel.MODULE_LICENSE("GPL") can access all the functions.
MODULE_AUTHOR("EMBEDDED GURUJI");
It specifies the author of the code.The importance of the macro is to know the author of the code when it is used by some other people.
static int hello_init(void)
{
printk("Hello World\n");
return 0;
}
hello_init() is a function which is registered to module_init and will be called when the driver is loaded.It just prints Hello World to the kernel message buffer.
static void hello_exit(void)
{
printk("Bye World\n");
}
hello_exit() is a function registered to module_exit and will be called when the driver is unloaded or removed.It prints Bye World to the kernel message buffer.
module_init(hello_init);
module_exit(hello_exit);
These are macros not functions. module_init() macro tells the kernel which function has to be called when the module is loaded.module_exit() macro tells the kernel which function has to be called when the module is unloaded.All the initializations has to be done in the function specified by module_init() and all the unintializations has to be done in the function specified by the module_exit() macro
Makefile contains the instructions for building the module.
obj-m := hello_world.o
obj-m := specifies the list of modules which has to be built.The .o files will be automatically be built from the .c source files.
KERNELDIR := /lib/modules/$(shell uname -r)/build
KERNELDIR is pointing to the location of the kernel source build folder
PWD := $(shell pwd)
PWD is pointing to the location of the current directory.
$(MAKE) -C $(KERNEL) M=$(PWD) modules
This specify to run make with the kernel source directory and build the modules present only in the PWD directory.
To install the module:
make
insmod hello_world.ko
To uninstall the module:
rmmod hello_world
Comments
Post a Comment