Thursday, August 28, 2025

Linux Device driver

 





1)      Any Linux driver has a constructor and a destructor.

2)      The module’s constructor is called when the module is successfully loaded into the kernel and the destructor when rmmod succeeds in unloading the module.

These two are like normal functions in the driver, except that they are specified as the init and exit functions, respectively, by the macros module_init() and module_exit(), which are defined in the kernel header module.h.

1)Simple driver(OFD)

Program for ofd:

#include <linux/module.h>

#include <linux/version.h>

#include <linux/kernel.h>

 static int __init ofd_init(void) /* Constructor */

{

    printk (KERN_INFO "Namaskar: ofd registered");

    return 0;

}

 static void __exit ofd_exit(void) /* Destructor */

{

    printk(KERN_INFO "Alvida: ofd unregistered");

}

 module_init(ofd_init);

module_exit(ofd_exit);

 MODULE_LICENSE("GPL");

MODULE_AUTHOR("");

 

MODULE_DESCRIPTION("Our First Driver");

Make file:

# Makefile – makefile of our first driver

 

# if KERNELRELEASE is defined, we've been invoked from the

# kernel build system and can use its language.

ifneq (${KERNELRELEASE},)

    obj-m := ofd.o

# Otherwise we were called directly from the command line.

# Invoke the kernel build system.

else

    KERNEL_SOURCE := /usr/src/linux

    PWD := $(shell pwd)

default:

    ${MAKE} -C ${KERNEL_SOURCE} SUBDIRS=${PWD} modules

 

clean:

    ${MAKE} -C ${KERNEL_SOURCE} SUBDIRS=${PWD} clean

Endif

 

With the C code (ofd.c) and Makefile ready, all we need to do is invoke make to build our first driver (ofd.ko).

$ make

make -C /usr/src/linux SUBDIRS=... modules

make[1]: Entering directory `/usr/src/linux'

  CC [M]  .../ofd.o

  Building modules, stage 2.

  MODPOST 1 modules

  CC      .../ofd.mod.o

  LD [M]  .../ofd.ko

make[1]: Leaving directory `/usr/src/linux'

 

To dynamically load or unload a driver, use these commands, which reside in the /sbin directory, and must be executed with root privileges:

  1.  insmod <module_file> — inserts/loads the specified module file

2.      Type d message can be seen by using the command

  dmesg

3.      rmmod<module_file> --- removes/unloads the module

 

4.      Type d message can be seen by using the command   dmesg


No comments: