Friday, July 23, 2010

Interprocess communications between a Linux Kernel Module (LKM) and a user program

More ofter than not a Kernel Module will need to communicate with a user program. We really have following three options for communication between a user program and Kernel Module:
  1. A device file in /dev
  2. A file in /proc 
  3. A file in /sysfs
  4. Netlink sockets
/dev is usually used for device driver files i.e files that represent devices but these don't have to be "real" devices, they can be pseudo devices. A device file in /dev/ may be acceptable, even for modules that aren't really device drivers. So if your module is a driver or exposes a simple open/read/write/close interface then this is the your best option.

A file in /proc or /sysfs is not an actual file. Read or write operations on these files actually go to the associated kernel module. /proc was originally intended for processes related information but over the years it has become dumping ground for lot of other stuff, which kernel developers are not happy about. So its better to stay away from it unless you are providing some processes related information. If you want a file based mechanism of communication but dont want to create a device file then /sysfs is the better option.

Netlink sockets, in my opinion, is the best option if you are working on a Kernel Module which is not a device driver. It provides user programs with a familiar socket interface and does not requires the creation of any kind of file.

I will soon be posting a working example of how to use Netlink socket for communication between a user program and Linux Kernel Module