c - 如何从 C 的 shell 脚本执行函数

标签 c bash shell

我有一个用户提供的脚本,比如

#!/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/

相关文章:

c - "int"真的需要至少与 C 中的 "short"一样大吗?

c - 警告 : '0' flag ignored with precision and ‘%i’ gnu_printf format

c - 为什么这允许从 (char *) 提升到 (const char *)?

linux - 这个表达式的计算结果是什么? (bash shell 脚本)

bash - 根据文本文件将文件移回原始位置

linux - ImageMagick 比较 shell 脚本好像挂了

shell - 在 *nix 命令行程序中等于与空间 ("-o=value"与 "-o value") - 最佳实践?

python - 在不占用键盘的情况下将击键发送到非事件的 GUI 应用程序

c - 将函数中局部(函数内)变量的引用返回给调用者

linux - 使 Unix shell 脚本符合 POSIX 标准