There are ways to communicate with Linux kernel, including /proc, debugfs, syscall and etc. Most of them are unidirectional, from the kernel to the user space. /proc could be used to ‘write’ to the kernel but mostly in small data transmission. The most flexible and reliable bidirectional communication should be netlink. This post will talk about netlink programming both in the kernel and the user space, using real working examples – nex. K.R.K.C.
1. netlink programming in the user space
This may be the most common way to do netlink programming. ‘man 7 netlink’/’man netlink’ should give the details and the concrete examples. Eventually, from the user space, netlink is a special socket, which means all you need to do is socket() and bind(). As long as there is a target socket address, send()/recv() should work. NOTE: the socket() should like this ‘socket(PF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);’. PF_NETLINK is the one for netlink; only UDP/raw works for netlink for the transport type. As the kernel has defined a lot of messages/protocols used to communicate with, the 3rd parameter should be the number standing for that message/protocol, like NETLINK_ROUTE.
2. netlink programming in the user space
If a new message/protocol is needed to talk to the kernel, which means there would be a user-defined message/protocol used by both the kernel and the user-space application, then netlink programming in the kernel space is needed. All the essential thing here is netlink_kernel_create() once the message is determined. Within this kernel function, a callback API used to process the message has to be provided. Once there is a netlink message from the user space, the netlink socket within the kernel space will receive it and process it using the callback API. NOTE: in the latest version of Linux kernel (3.9/3.10), to create a netlink socket in the kernel, your could should look like below:
But the older version (2.6/3.X) may look like this: