I am working on netlink sockets, written code for application and kernel module. Kernel module will send notifications regularly to user space application. If application gets killed, kernel module doesn't stop sending notification. How the kernel will know when application gets killed? Can we user bind and unbind in netlink_kernel_cfg for this purpose? I have searched a lot but didn't find any information on this.
1 Answers
When any application is killed in Linux, all file descriptors (including socket descriptors) are closed. In order to have your kernel module notified when the application closes the netlink socket you need to implement the optional .unbind op in struct netlink_kernel_cfg.
include/linux/netlink.h
/* optional Netlink kernel configuration parameters */
struct netlink_kernel_cfg {
unsigned int groups;
unsigned int flags;
void (*input)(struct sk_buff *skb);
struct mutex *cb_mutex;
int (*bind)(struct net *net, int group);
void (*unbind)(struct net *net, int group);
bool (*compare)(struct net *net, struct sock *sk);
};
Set the configuration parameters in your module:
struct netlink_kernel_cfg cfg = {
.unbind = my_unbind,
};
netlink = netlink_kernel_create(&my_netlink, ... , &cfg);
To understand how this is used, note the following fragment from the netlink protocol family proto_ops definition:
static const struct proto_ops netlink_ops = {
.family = PF_NETLINK,
.owner = THIS_MODULE,
.release = netlink_release,
.release is called upon close of the socket (in your case, due to the application being killed).
As a part of its cleanup process, netlink_release() has the following implementation:
net/netlink/af_netlink.c
if (nlk->netlink_unbind) {
int i;
for (i = 0; i < nlk->ngroups; i++)
if (test_bit(i, nlk->groups))
nlk->netlink_unbind(sock_net(sk), i + 1);
Here you can see that if the optional netlink_unbind has been provided, then it will be executed, providing you a callback when your application has closed the socket (either gracefully or as a result of being killed).

- 23
- 6