内核运行一个用户程序

本文最后更新于:2025年11月19日 下午

使用call_usermodehelper即可。

函数原型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* call_usermodehelper() - prepare and start a usermode application
* @path: path to usermode executable
* @argv: arg vector for process
* @envp: environment for process
* @wait: wait for the application to finish and return status.
* when UMH_NO_WAIT don't wait at all, but you get no useful error back
* when the program couldn't be exec'ed. This makes it safe to call
* from interrupt context.
*
* This function is the equivalent to use call_usermodehelper_setup() and
* call_usermodehelper_exec().
*/
int call_usermodehelper(const char *path, char **argv, char **envp, int wait)

第4个参数wait取值如下:

1
2
3
4
#define UMH_NO_WAIT	0	/* don't wait at all */
#define UMH_WAIT_EXEC 1 /* wait for the exec, but not the process */
#define UMH_WAIT_PROC 2 /* wait for the process to complete */
#define UMH_KILLABLE 4 /* wait for EXEC/PROC killable */

例子

1
2
3
4
5
6
7
8
9
10
void run_users_proc(void)
{
char *argv[] = {"/bin/sh", "-c", "/etc/test.sh > /dev/console", NULL};
char *envp[] = {"PATH=/sbin:/bin:/usr/sbin:/usr/bin", "HOME=/", NULL};
int ret = 0;

printk(" run .... \n\n");
ret = call_usermodehelper(argv[0], argv, envp, UMH_WAIT_PROC);
printk("ret = %d\n", ret);
}

因为从内核打开的程序,并没有人为其准备标准输入输出,所以上面例子重定向console,才能有输出。


人生苦短,远离bug Leon, 2024-04-17

内核运行一个用户程序
https://leon0625.github.io/2024/04/17/171ada44f455/
作者
leon.liu
发布于
2024年4月17日
许可协议