Linux内核通知链

===============================   博客点滴积累,部分话语和知识点来源于网络,感谢网络资源的提供者======


linux 内核通知链,是一种异步通信机制,类似发布者-订阅者模式,Linux内核通知链实现说简单点就是:一个单向链表的插入,删除,遍历。

所在文件Notifier.c /Notifier.h  

看看代码:

通知链结构体

struct notifier_block {

int (*notifier_call)(struct notifier_block *, unsigned long, void *);//函数指针

struct notifier_block *next;//链表指针

int priority; //优先级,优先级高的函数会优先遍历

};

2 主要实现函数

/*注册函数,就是单链表的插入排序*/

static int notifier_chain_register(struct notifier_block **nl,
struct notifier_block *n)
{

while ((*nl) != NULL) {//链表是否为空

if (n->priority > (*nl)->priority)//找到合适的位置,优先级高的插入到链表的前面

break;

nl = &((*nl)->next);//遍历到下一个元素

}

n->next = *nl;

rcu_assign_pointer(*nl, n);

return 0;

}
//注销函数,链表的删除
static int notifier_chain_unregister(struct notifier_block **nl,
struct notifier_block *n)
{

while ((*nl) != NULL) {

if ((*nl) == n) {

rcu_assign_pointer(*nl, n->next);

return 0;

}

nl = &((*nl)->next);

}

return -ENOENT;

}

//遍历回调处理函数,也是链表的遍历
static int __kprobes notifier_call_chain(struct notifier_block **nl,
unsigned long val, void *v,int nr_to_call,int *nr_calls)
{

int ret = NOTIFY_DONE;

struct notifier_block *nb, *next_nb;

nb = rcu_dereference(*nl);

while (nb && nr_to_call) {

next_nb = rcu_dereference(nb->next);

ret = nb->notifier_call(nb, val, v);//回调处理函数

if (nr_calls)

(*nr_calls)++;

if ((ret & NOTIFY_STOP_MASK) == NOTIFY_STOP_MASK)

break;

nb = next_nb;

nr_to_call--;

}

return ret;

}

3linux 内核通知链,根据安全措施的不同,主要分为四种:

原子通知

struct atomic_notifier_head {

spinlock_t lock;

struct notifier_block *head;

};

可阻塞通知
struct blocking_notifier_head {

struct rw_semaphore rwsem;

struct notifier_block *head;

};

原始通知
struct raw_notifier_head {

struct notifier_block *head;

};
类似阻塞通知

struct srcu_notifier_head {

struct mutex mutex;

struct srcu_struct srcu;

struct notifier_block *head;

};

对应这几个注册,注销函数,遍历回调函数,只是对上边的函数进行了一定的封装

4 下边是定义一个通知链头,并初始化

#define ATOMIC_INIT_NOTIFIER_HEAD(name) do {\

spin_lock_init(&(name)->lock);\

(name)->head = NULL;\

} while (0)
#define BLOCKING_INIT_NOTIFIER_HEAD(name) do { \

init_rwsem(&(name)->rwsem);\

(name)->head = NULL;\

} while (0)
#define RAW_INIT_NOTIFIER_HEAD(name) do { \

(name)->head = NULL;\

} while (0)

#define ATOMIC_INIT_NOTIFIER_HEAD(name) do {\

spin_lock_init(&(name)->lock);\

(name)->head = NULL;\

} while (0)
#define BLOCKING_INIT_NOTIFIER_HEAD(name) do { \

init_rwsem(&(name)->rwsem);\

(name)->head = NULL;\

} while (0)
#define RAW_INIT_NOTIFIER_HEAD(name) do { \

(name)->head = NULL;\

} while (0)

5 如何使用?真的很简单,没什么好说的, 事件A 和 事件B,  当A发生变化后,B事件希望能收到通知,那么B向A通知链注册回调函数,当A发生变化,遍历链表调用回调函数,通知事件B

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值