【问题标题】:How kernel knows the presence of netlink in userspace?内核如何知道用户空间中 netlink 的存在?
【发布时间】:2017-05-19 10:21:36
【问题描述】:

我正在研究 netlink 套接字,为应用程序和内核模块编写代码。内核模块会定期向用户空间应用程序发送通知。如果应用程序被杀死,内核模块不会停止发送通知。内核如何知道应用程序何时被杀死?我们可以为此目的在 netlink_kernel_cfg 中用户绑定和取消绑定吗?我搜索了很多,但没有找到任何相关信息。

【问题讨论】:

    标签: linux-kernel netlink


    【解决方案1】:

    当任何应用程序在 Linux 中被终止时,所有文件描述符(包括套接字描述符)都将关闭。为了在应用程序关闭 netlink 套接字时通知您的内核模块,您需要在 struct netlink_kernel_cfg中实现可选的 .unbind 操作>

    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);
    };
    

    在你的模块中设置配置参数:

    struct netlink_kernel_cfg cfg = {
            .unbind = my_unbind,
    };
    
    netlink = netlink_kernel_create(&my_netlink, ... , &cfg);
    

    要了解它是如何使用的,请注意 netlink 协议族 proto_ops 定义中的以下片段:

    static const struct proto_ops netlink_ops = {
            .family =       PF_NETLINK,
            .owner =        THIS_MODULE,
            .release =      netlink_release,
    

    .release 在关闭套接字时调用(在您的情况下,由于应用程序被杀死)。

    作为其清理过程的一部分,netlink_release() 具有以下实现:

    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);
    

    在这里你可以看到如果提供了可选的netlink_unbind,那么它将被执行,当你的应用程序关闭套接字时为你提供一个回调(优雅地或被杀)。

    【讨论】:

      猜你喜欢
      • 2011-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-05
      • 2014-05-06
      • 1970-01-01
      相关资源
      最近更新 更多