notifier涉及:
1,publisher,类比于server、provider等概念,负责:
- 提供一个notifier head链表供subscriber注册handler
- 遍历head链表逐一告知subscriber发生了某个事件
2,subscriber,类比于client、consumer等概念,接收到publisher的事件通知后开行自己的工作
实例:
kernel中针对reboot提供了一个notifier:
notifier.h (include\linux)
extern struct blocking_notifier_head reboot_notifier_list;
sys.c (kernel)
/**
* register_reboot_notifier - Register function to be called at reboot time
* @nb: Info about notifier function to be called
*/
int register_reboot_notifier(struct notifier_block *nb)
接下来我们实现一个自己的notifier来接收reboot事件:
static int mynotifier_fn(struct notifier_block *nb, unsigned long action, void *data)
{
printk("%s action: %d\n", __func__, action);
return NOTIFY_OK;
}
static struct notifier_block mynotifier = {
.notifier_call = mynotifier_fn,
};
static int mynotifier_init(void)
{
printk("%s enter\n", __func__);
return register_reboot_notifier(&mynotifier);
}
late_initcall(mynotifier_init);
reboot后将会接收到这个reboot通知,在handler函数中这里仅仅打印了下action值:
详细资料,参考:
The Crux of Linux Notifier Chains
Linux is monolithic like any other kernel. Its subsystems or modules help to keep the kernel light by being flexible enough to load and unload at runtime. In most cases, the kernel modules are interconnected to one another. An event captured by a certain module might be of interest to another module. For instance, when a USB device is plugged to your kernel, the USB core driver has to communicate to the bus driver sitting at the top. This will allow the bus driver to take care of the rest. Another classic example would be of interfaces. Many kernel modules would be looking for a network interface state change. The lower level module that detects the network interface state change, would communicate this information to the other modules.
Typically, communication systems implement request-reply messaging, or polling. In such models, a program that receives a request will have to send the data available since the last transaction. Such methods sometimes require high bandwidth or they waste polling cycles.
Linux uses a notifier chain, a simple list of functions that is executed when an event occurs. These notifier chains work in a publish-subscribe model. This model is more effective when compared to polling or the request-reply model. In a publish-subscribe model, the ‘client’ (subscriber) that requires notification of a certain event, ‘registers’ itself with the ‘server’ (publisher). The server will inform the client whenever an event of interest occurs. Such a model reduces the bandwidth requirement or the polling cycle requirement, as the client