简体   繁体   English

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

[英]How to execute a function from a shell-script from C

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 代码调用函数 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() 执行它,但我正在寻找一个更优雅,尤其是更通用的解决方案,它可以让我执行任意命名的函数,甚至可以让我获取/设置变量。

You cannot do this directly from C. However, you can use system to run a command (like sh ) from C:您不能直接从 C 执行此操作。但是,您可以使用system从 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 ' command '允许您在 shell 中运行command 。)

Alternatively, you can also use execlp or some other function from the exec family:或者,您也可以使用execlpexec系列中的其他一些函数:

// 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"必须重复

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 $1 , eg你可以这样做,如果你将函数作为参数提供给shell脚本并且在最后一行只有$1 ,例如

fun1()
{
    echo "fun1 called"
}

fun2()
{
    echo "fun2 called"
}

$1

You can then call your script as然后您可以将您的脚本称为

sh userscript.sh fun1

which gives这使

fun1 called fun1 调用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM