如何从 C 代码加载 Linux 内核模块?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5947286/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to load Linux kernel modules from C code?
提问by Prof. Moriarty
I have an application that has both two external kernel modules and a userspace daemon. I want to load the modules from the daemon code, written in C, at startup, and unload them on clean exit. Can I load them in a cleaner way than doing system("modprobe module");
and unload them using the corresponding rmmod
?
我有一个具有两个外部内核模块和一个用户空间守护进程的应用程序。我想在启动时从用 C 编写的守护程序代码加载模块,并在干净退出时卸载它们。我可以以比system("modprobe module");
使用相应的方式卸载和卸载它们更干净的方式加载它们rmmod
吗?
回答by Michael Foukarakis
You can perform the same tasks that modprobe
and Co. do, but I doubt that could be characterized as cleaner.
您可以执行modprobe
和 Co. 所做的相同任务,但我怀疑这是否可以称为更清洁。
回答by Didier Trosset
I'm not sure there's a cleanerway than system
.
我不知道有一个更清洁的方式比system
。
But for sure, if you want to load/unload the modules from your userspace daemon, then you force yourself to run the daemon as root*, which may not be considered as secure.
但可以肯定的是,如果您想从用户空间守护程序加载/卸载模块,那么您必须强制自己以 root* 身份运行守护程序,这可能不被认为是安全的。
*: or you can add the explicit commands in the sudoers file, but this will be a nightmare to manage when deploying your application.
*: 或者您可以在 sudoers 文件中添加显式命令,但这将是部署应用程序时管理的噩梦。
回答by Rakis
I'd recommend against the use of system()
in any daemon code that runs with root permissions as it's relatively easy to exploit from a security standpoint. modprobe
and rmmod
are, indeed, the right tools for the job. However, it'd be a bit cleaner and much more secure to use an explicit fork()
+ exec()
to invoke them.
我建议不要system()
在任何以 root 权限运行的守护程序代码中使用 ,因为从安全角度来看它相对容易被利用。modprobe
并且rmmod
确实是完成这项工作的正确工具。但是,使用显式fork()
+exec()
来调用它们会更简洁、更安全。
回答by filmor
insmod/rmmod use the functions init_module
and delete_module
to do this, which also have a man-page available. They both declare the functions as extern
instead of including a header, but the man-page says they should be in <linux/module.h>
.
insmod的/ rmmod的使用功能init_module
,并delete_module
要做到这一点,这也有个男人页可用。它们都将函数声明为extern
而不是包含标题,但手册页说它们应该在<linux/module.h>
.