[英]How can I call a function defined in a bash shell script from a C program
I have 我有
#!/bin/sh
func1()
{
echo "This is func1 from shell script"
}
func2()
{
echo "This is func2 from shell script"
}
I want to call func1 and func2 from a C program. 我想从C程序调用func1和func2。 Can I do that ? 我可以那样做吗?
This is unlikely to be a good idea, but I suppose you could write something like this: 这不太可能是一个好主意,但我想您可以这样写:
if (! fork()) { // TODO fork can return -1 on error; should check for that
execl("/bin/sh", "-c", ". FILE && func1", (char *)NULL);
// TODO should check to make sure execlp successfully replaced the process
}
where FILE
is the name of the .sh
file that defines func1
. 其中FILE
是定义func1
的.sh
文件的名称。 The above will spawn a child process, and replace that child process with an instance of Bash (or whatever your shell is) with the arguments -c
(meaning "the script to run is the next argument") and . FILE && func1
上面的代码将生成一个子进程,并用参数-c
(表示“要运行的脚本是下一个参数”)和Bash实例替换为Bash(或任何您的外壳)实例. FILE && func1
. FILE && func1
(which is the script; it means "run the commands in FILE
, and if that succeeds, then run the command func1
"). . FILE && func1
(这是脚本;它的意思是“在FILE
运行命令,如果成功,则运行命令func1
”)。
For more information: 欲获得更多信息:
A little simpler than using fork / exec is the stdlib "system" command. 比使用fork / exec更简单的是stdlib“ system”命令。
See man 3 system . 参见man 3系统 。
Assume your bash functions are in file "/tmp/scripts.sh" ... 假设您的bash函数在文件“ /tmp/scripts.sh”中...
system("bash -c \". /tmp/scripts.sh ; func1 ; func2\"");
如果要获取执行脚本的退出代码,则应使用system,否则使用vfork + exec *
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.