简体   繁体   English

在C中注册回调函数

[英]Registering a callback function in C

I am some Linux kernel space code. 我是一些Linux内核空间代码。 I want an application in user space to be able to register a callback function in the kernel space code by calling a function in the kernel space code and passing the address of that callback function. 我希望用户空间中的应用程序能够通过调用内核空间代码中的函数并传递该回调函数的地址来在内核空间代码中注册回调函数。 The kernel space code would then execute the callback function at a later time when running. 然后,内核空间代码将在以后运行时执行回调函数。 I believe the kernel space code should look something like this: 我相信内核空间代码看起来像这样:

typedef void (*callback_func) (void);
callback_func callback;

static void registerCallBack(callback_func funct){callback = funct;}

//another kernel space method
funct();

However, I am a little unsure on the proper typedef and if this will work properly. 但是,我对正确的typedef有点不确定,如果这样可以正常工作。 Can anyone confirm the functionality of this or offer any advice in this area? 任何人都可以确认这个功能或在这个领域提供任何建议吗? I am unable to test this right now as I am waiting on the rest of the kernel space code to be finished. 我现在无法测试这个,因为我正在等待剩余的内核空间代码完成。

你的typedef看起来很好,虽然我建议将callback_func重命名为callback_func_t ,否则它看起来像一个变量而不是一个类型。

You cannot directly call to a userspace function from the kernel. 您无法直接从内核调用用户空间函数。 One possible solution would be to use signals . 一种可能的解决方案是使用信号 From the kernel code you could send a signal to a given process. 从内核代码中,您可以向给定进程发送信号。 The signal handler would work then as a sort of callback function. 然后信号处理程序将作为一种回调函数工作。

If you simply want to run a user-space application from the kernel, then this describes how to do that in detail. 如果您只是想从内核运行用户空间应用程序,那么将详细描述如何执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM