我有一个用户提供的脚本,比如
#!/bin/sh
some_function () {
touch some_file
}
some_other_function () {
touch some_other_file
}
我想从 C 代码调用函数 some_other_function。
我知道,我可以简单地编写一个 shell 脚本,例如
#!/bin/sh
source userscript.sh
some_other_function
并使用 system() 执行它,但我正在寻找一种更优雅、尤其是更通用的解决方案,它可以让我执行任意命名的函数,甚至可以让我获取/设置变量。
最佳答案
您不能直接从 C 执行此操作。但是,您可以使用 system
从 C: 运行命令(如 sh
)
// Run the command: sh -c 'source userscript.sh; some_other_function'
system("sh -c 'source userscript.sh; some_other_function'");
(请注意 sh -c '<em>command</em>'
允许您在 shell 中运行 <em>command</em>
。)
或者,您也可以使用 execlp
或来自 exec
的一些其他功能家庭:
// Run the command: sh -c 'source userscript.sh; some_other_function'
execlp("sh", "sh", "-c", "source userscript.sh; some_other_function", NULL);
(注意这里使用 exec
函数时,第一个参数 – "sh"
– 必须重复)
关于c - 如何从 C 的 shell 脚本执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23068866/