如何在Linux内核中执行某些用户态程序或系统命令?在用户态中,可以通过execve()实现;在内核态,则可以通过call_usermodehelpere()实现该功能。如果您查阅了call_usermodehelper()内核函数的源码实现,就可以发现该函数最终会执行do_execve()。而execve系统调用在经历内核的系统调用流程后,也会最终调用do_execve()。
代码实例
1 内核态调用用户态reboot命令
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
static int __init test_init(void){
int ret=-1;
char path[]="/sbin/reboot";
char *argv[]={path,NULL};
char *envp[]={NULL};
printk("call_usermodehelper module isstarting..!\n");
ret = call_usermodehelper(path, argv, envp,UMH_WAIT_PROC);
printk("ret=%d\n", ret);
return 0;
}
static void __exit test_exit(void){
}
module_init(test_init);
module_exit(test_exit);
MODULE_LICENSE("GPL");