I have a user supplied script like
我有一个用户提供的脚本,如
#!/bin/sh
some_function () {
touch some_file
}
some_other_function () {
touch some_other_file
}
and i want to call the function some_other_function from c-code.
我想从c-code调用函数some_other_function。
I understand, that i could simply write a shell script like
我明白,我可以简单地编写一个shell脚本
#!/bin/sh
source userscript.sh
some_other_function
and execute it using system(), but i am looking for a more elegant and especially a more generic solution, that lets me execute arbitrarily named functions and maybe even lets me get/set variables.
并使用system()执行它,但我正在寻找一个更优雅,尤其是更通用的解决方案,让我可以执行任意命名的函数,甚至可以让我获取/设置变量。
2 个解决方案
#1
2
You cannot do this directly from C. However, you can use system
to run a command (like sh
) from C:
您不能直接从C执行此操作。但是,您可以使用系统从C运行命令(如sh):
// Run the command: sh -c 'source userscript.sh; some_other_function'
system("sh -c 'source userscript.sh; some_other_function'");
(Note that the sh -c 'command'
lets you run command
in a shell.)
(注意,sh -c'命令'允许你在shell中运行命令。)
Alternatively, you can also use execlp
or some other function from the exec
family:
或者,您也可以使用execp或exec系列中的其他函数:
// Run the command: sh -c 'source userscript.sh; some_other_function'
execlp("sh", "sh", "-c", "source userscript.sh; some_other_function", NULL);
(Note here that when using exec
functions, the first argument – "sh"
– must be repeated)
(注意这里使用exec函数时,必须重复第一个参数 - “sh” - )
#2
1
From the comments, I understand that you want to call one of several functions defined in your script. You can do this, if you give the function as an argument to the shell script and in the last line just have
从评论中,我了解到您想要调用脚本中定义的几个函数之一。如果将函数作为shell脚本的参数并在最后一行中提供,则可以执行此操作
$1
You can then call your script as
然后,您可以将脚本调用为
sh userscript.sh some_function
#1
2
You cannot do this directly from C. However, you can use system
to run a command (like sh
) from C:
您不能直接从C执行此操作。但是,您可以使用系统从C运行命令(如sh):
// Run the command: sh -c 'source userscript.sh; some_other_function'
system("sh -c 'source userscript.sh; some_other_function'");
(Note that the sh -c 'command'
lets you run command
in a shell.)
(注意,sh -c'命令'允许你在shell中运行命令。)
Alternatively, you can also use execlp
or some other function from the exec
family:
或者,您也可以使用execp或exec系列中的其他函数:
// Run the command: sh -c 'source userscript.sh; some_other_function'
execlp("sh", "sh", "-c", "source userscript.sh; some_other_function", NULL);
(Note here that when using exec
functions, the first argument – "sh"
– must be repeated)
(注意这里使用exec函数时,必须重复第一个参数 - “sh” - )
#2
1
From the comments, I understand that you want to call one of several functions defined in your script. You can do this, if you give the function as an argument to the shell script and in the last line just have
从评论中,我了解到您想要调用脚本中定义的几个函数之一。如果将函数作为shell脚本的参数并在最后一行中提供,则可以执行此操作
$1
You can then call your script as
然后,您可以将脚本调用为
sh userscript.sh some_function