Bash脚本非常有用,可以节省大量编程时间。那么,如何在C++程序中启动bash脚本呢?另外,如果你知道如何让用户成为超级用户,那将是很好的。谢谢!
发布于 2009-03-14 16:45:32
使用system
函数。
system("myfile.sh"); // myfile.sh should be chmod +x
发布于 2009-03-14 16:46:17
#include <stdio.h>
#include <stdlib.h>
// ....
system("my_bash_script.sh");
发布于 2017-08-05 19:27:53
因为这是一个非常老的问题,而且还没有添加这个方法(除了system()
调用函数),我想包含用C二进制文件本身创建shell脚本会很有用。外壳代码将包含在file.c
源文件中。下面是一个代码示例:
#include <stdio.h>
#include <stdlib.h>
#define SHELLSCRIPT "\
#/bin/bash \n\
echo -e \"\" \n\
echo -e \"This is a test shell script inside C code!!\" \n\
read -p \"press <enter> to continue\" \n\
clear\
"
int main() {
system(SHELLSCRIPT);
return 0;
}
基本上,简而言之(双关语),我们定义脚本名称,充实脚本,将它们括在双引号中(同时插入适当的转义以忽略外壳代码中的双引号),然后调用脚本的名称,在本例中为SHELLSCRIPT
,使用main()
中的system()
函数。
https://stackoverflow.com/questions/646217
复制相似问题